131

Node.JS如何查看本地MAC/IP地址、计算cpu使用率和内存容量

 6 years ago
source link: http://ourjs.com/detail/5a603e363506837194998bfa?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Node.JS的OS提供了一系统CPU/内存/网络相关的接口,通过它我们可以查看本地的网络配置。使用起来非常简单

本地MAC和IP地址

var os = require('os')
console.log(os.networkInterfaces())
输出结果:
{
  lo: [
    {
      address: '127.0.0.1',
      netmask: '255.0.0.0',
      family: 'IPv4',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: '127.0.0.1/8'
    },
    {
      address: '::1',
      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: '::1/128'
    }
  ],
  eth0: [
    {
      address: '192.168.1.108',
      netmask: '255.255.255.0',
      family: 'IPv4',
      mac: '01:02:03:0a:0b:0c',
      internal: false,
      cidr: '192.168.1.108/24'
    }
  ]
}
内存的容量和已用内存
var freemem   = os.freemem()
var totalmem  = os.totalmem()
var usedmem   = totalmem - freemem

CPU情况和使用率

cpus返回CPU情况,返回的是一个数组,有多少个核心就有多少个元素。
var cpus = os.cpus()
console.log(cpus)
[
  {
    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
    speed: 2926,
    times: {
      user: 252020,
      nice: 0,
      sys: 30340,
      idle: 1070356870,
      irq: 0
    }    
  }
  ...
]
使用率略为复杂,有一个loadavg方法,计算过去十几分钟的平均使用率,但目前并不支持Windows
os.loadavg()
其实我们可以用之前的cpus()方法来计算出,即通过idle和总时间的比值得出时时使用率
cpuIAverage = function(i) {
  var cpu, cpus, idle, len, total, totalIdle, totalTick, type;
  totalIdle = 0;
  totalTick = 0;
  cpus = os.cpus();
  cpu = cpus[i];
  for (type in cpu.times) {
    totalTick += cpu.times[type];
  }
  totalIdle += cpu.times.idle;
  idle = totalIdle / cpus.length;
  total = totalTick / cpus.length;
  return {
    idle: idle,
    total: total
  };
};
更多计算使用率的函数: https://gist.github.com/bag-man/5570809

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK