os模块,可以用来获取操作系统相关的信息和机器物理信息,例如操作系统平台,内核,cpu架构,内存,cpu,网卡等信息。
使用如下所示:
const os = require('os');
var dealTime = (seconds)=>{
var seconds = seconds|0;
var day = (seconds/(3600*24))|0;
var hours = ((seconds-day*3600)/3600)|0;
var minutes = ((seconds-day*3600*24-hours*3600)/60)|0;
var second = seconds%60;
(day<10)&&(day='0'+day);
(hours<10)&&(hours='0'+hours);
(minutes<10)&&(minutes='0'+minutes);
(second<10)&&(second='0'+second);
return [day,hours,minutes,second].join(':');
};
var dealMem = (mem)=>{
var G = 0,
M = 0,
KB = 0;
(mem>(1<<30))&&(G=(mem/(1<<30)).toFixed(2));
(mem>(1<<20))&&(mem<(1<<30))&&(M=(mem/(1<<20)).toFixed(2));
(mem>(1<<10))&&(mem>(1<<20))&&(KB=(mem/(1<<10)).toFixed(2));
return G>0?G+'G':M>0?M+'M':KB>0?KB+'KB':mem+'B';
};
//cpu架构
const arch = os.arch();
console.log("cpu架构:"+arch);
//操作系统内核
const kernel = os.type();
console.log("操作系统内核:"+kernel);
//操作系统平台
const pf = os.platform();
console.log("平台:"+pf);
//系统开机时间
const uptime = os.uptime();
console.log("开机时间:"+dealTime(uptime));
//主机名
const hn = os.hostname();
console.log("主机名:"+hn);
//主目录
const hdir = os.homedir();
console.log("主目录:"+hdir);
//内存
const totalMem = os.totalmem();
const freeMem = os.freemem();
console.log("内存大小:"+dealMem(totalMem)+' 空闲内存:'+dealMem(freeMem));
//cpu
const cpus = os.cpus();
console.log('*****cpu信息*******');
cpus.forEach((cpu,idx,arr)=>{
var times = cpu.times;
console.log(`cpu${idx}:`);
console.log(`型号:${cpu.model}`);
console.log(`频率:${cpu.speed}MHz`);
console.log(`使用率:${((1-times.idle/(times.idle+times.user+times.nice+times.sys+times.irq))*100).toFixed(2)}%`);
});
//网卡
console.log('*****网卡信息*******');
const networksObj = os.networkInterfaces();
for(let nw in networksObj){
let objArr = networksObj[nw];
console.log(`
${nw}:`);
objArr.forEach((obj,idx,arr)=>{
console.log(`地址:${obj.address}`);
console.log(`掩码:${obj.netmask}`);
console.log(`物理地址:${obj.mac}`);
console.log(`协议族:${obj.family}`);
});
}
执行结果如下:
E:developmentdocument
odejsdemo>node os-example.js
cpu架构:x64
操作系统内核:Windows_NT
平台:win32
开机时间:00:09:18:08
主机名:test-PC
主目录:C:Users est
内存大小:3.90G 空闲内存:1.42G
cpu信息**
cpu0:
型号:Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz
频率:3192MHz
使用率:7.32%
cpu1:
型号:Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz
频率:3192MHz
使用率:5.80%
cpu2:
型号:Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz
频率:3192MHz
使用率:6.31%
cpu3:
型号:Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz
频率:3192MHz
使用率:6.37%
网卡信息**
本地连接:
地址:fe80::c409:72be:75f8:2d01
掩码:ffff:ffff:ffff:ffff::
物理地址:40:8d:5c:b8:da:df
协议族:IPv6
地址:1.1.1.69
掩码:255.255.255.0
物理地址:40:8d:5c:b8:da:df
协议族:IPv4
Loopback Pseudo-Interface 1:
地址:::1
掩码:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
物理地址:00:00:00:00:00:00
协议族:IPv6
地址:127.0.0.1
掩码:255.0.0.0
物理地址:00:00:00:00:00:00
协议族:IPv4
6TO4 Adapter:
地址:2002:101:145::101:145
掩码:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
物理地址:00:00:00:00:00:00
协议族:IPv6
E:developmentdocument odejsdemo>