node获取设备硬件信息os模块

2019-10-09  本文已影响0人  码上行动
//开启严格模式
'use strict';

const os = require('os');

function deviceInfo() {
    if (!os) {
        return null;
    }

    const info = {
        platform: '',
        hostname: '',
        cpu: '',
        mac: ''
    };

//操作系统平台
    const pf = os.platform();

    switch (pf) {
        case 'darwin':
            info.platform = 'macOS'
            break;
        case 'win32':
            info.platform = 'Windows'
            break;
        default:
            break;
    }

    //主机名
    info.hostname = os.hostname();

    //cpu
    const cpus = os.cpus();
    if (cpus.length) {
        info.cpu = cpus[0].model;
    }

    //网卡
    const netmap = os.networkInterfaces();
    const conf = ['en0', 'WLAN', '以太网'];

    // console.log(netmap);

    for (let index = 0; index < conf.length; index++) {
        const key = conf[index];
        const item = netmap[key];
        if (item) {
            info.mac = item[0].mac
            // console.log('mac:'+ mac);
            break;
        }
    }

    return info;
}
//module.exports 暴露接口的方法
module.exports = {
    deviceInfo: deviceInfo
};

调用

var device = require('./js/nwjs.device');
            console.log(JSON.stringify(device.deviceInfo()))
            window.deviceInfo = device.deviceInfo();
            //获取设备信息
            $.ajax({
                type: "POST",                
                             url:'http://192.168.31.218:8020/device/uploadDeviceInfo',
                dataType: "json",
                data: JSON.stringify(window.deviceInfo),
                contentType:'application/json',
                cache: false,
                global: false,
                success: function (json) {
                    console.log(json)
                },
                error: biz.ajaxError
            });

详情参照node官方文档os模块篇

http://nodejs.cn/api/os.html

上一篇 下一篇

猜你喜欢

热点阅读