nodejs 获取内存,网络 ,连接 ,磁盘等等

完整的程序链接下载

util

建立一个util,计算使用

var utils = {}
utils.humanFileSize = function(bytes, isDecimal) {
  isDecimal = (typeof isDecimal !== 'undefined') ? isDecimal : false;
  if (bytes == 0) {
    return "0.00 B";
  }
  var base = isDecimal ? 1000 : 1024;
  var e = Math.floor(Math.log(bytes) / Math.log(base));
  return (bytes / Math.pow(base, e)).toFixed(2) + ' ' + ' KMGTP'.charAt(e) + (isDecimal || e == 0 ? '' : 'i') + 'B';
}

utils.colors = ['magenta', 'cyan', 'blue', 'yellow', 'green', 'red'];

module.exports = utils;

进程

所有进程
/**
 * author :钱波
 * 抓取所有进程
 * */

var si = require('systeminformation'),
  utils = require('./utils');
var hashmap = require('hashmap')
//var colors = utils.colors;

class proc_class {
//var hashmap
    say(callback) {
        si.processes()
            .then(data => {
                //var pu = [];
                this.hashmap_pid = new hashmap();
                this.array = [];
                var data1 = data.list
                    .map(p => {
                        var value = {
                            pid: p.pid,
                            cmd: p.name, //.slice(0,10),
                            cpuuse: p.pcpu.toFixed(1),
                            memuse: p.pmem.toFixed(1)
                        }
                        this.hashmap_pid.set('"'+p.pid+'"', value)
                        this.array.push(value);

                        //pu.push()
                    })
                if (callback != null) {
                   // console.log("...start to print...",this.hashmap_pid);
                    callback(this.array);
                }
            })
            .catch(error => console.error(error));
    }

    getpidname(id) {
        //console.log("hashmap", this.hashmap_pid);
        //console.log("want to find", id);
        let test = this.hashmap_pid.get(id);
        //console.log("test is ", test);
        if (test != null) {
            return test.cmd;
            //console.log("find it",test);
        }
        return null;     
        //return this.hashmap_pid;
    }

}


## 网络
module.exports = new proc_class();
/*
 * unit test
//function call(data) {
//    console.log(data);
//}
//var proc = new proc_class();
//proc.say(call);
*/
var si = require('systeminformation'),
    utils = require('./utils');
class net_class {
    updateData(data,callback) {
        //console.log(data);
        var rx_sec = Math.max(0, data['rx_sec']);
        var tx_sec = Math.max(0, data['tx_sec']);

        //this.netData[0].shift();
        //this.netData[0].push(rx_sec);

        //this.netData[1].shift();
        //this.netData[1].push(tx_sec);

        //rx_label = 'Receiving:      ' +
        //    utils.humanFileSize(rx_sec) +
        //    '/s \nTotal received: ' +
        //    utils.humanFileSize(data['rx_bytes']);

        //tx_label = 'Transferring:      ' +
        //    utils.humanFileSize(tx_sec) +
        //    '/s \nTotal transferred: ' +
        //    utils.humanFileSize(data['tx_bytes']);

        if (callback != null) {
            callback(
                {
                    rxsec: utils.humanFileSize(rx_sec),
                    txsec: utils.humanFileSize(tx_sec),
                    total_r: utils.humanFileSize(data['rx_bytes']),
                    total_s: utils.humanFileSize(data['tx_bytes'])
                }
            )
        }

    };


    say(callback) {
        si.networkInterfaceDefault(iface => {
            var that = this;
            var updater = function () {
                si.networkStats(iface, data => {
                    that.updateData(data[0],callback);
                });
            }
            updater();
        })
    }
}
module.exports = new net_class();

磁盘

/**
 * author :钱波
 * 抓取所有磁盘,注意不适合windows
 * */

var si = require('systeminformation'),
  utils = require('./utils');

//var colors = utils.colors;
class disk_class {

    say(callback) {
        si.fsSize()
            .then(data => {
                var disk = data[0];
                //console.log(disk)

                data = [{
                    use: utils.humanFileSize(disk.used, true),
                    size: utils.humanFileSize(disk.size, true),
                    percent: disk.use / 100
                }];
                if (callback != null)
                    callback(data);
            })
            .catch(error => console.error(error))

    }

}

module.exports = new disk_class();
//unit test
//function call(data) {
//    console.log(data);
//}
//var disk = new disk_class();
//disk.say(call);

//module.exports = Disk;

cpu

var si = require('systeminformation');

var hashmap = require('hashmap')
class cpu_class{
    constructor() {
        this.cpumap = new hashmap();
        si.currentLoad()
            .then(data => {
                
                data.cpus.map((cpu, i) => {
                    var x = Array(61).fill(0);
                    this.cpumap.set("CPU" + i+1, x);
                    //console.log(cpu.load);
                })
            })
            .catch(error => console.error(error))
    }
    say(callback) {
        si.currentLoad()
            .then(data => {
                if (callback != null)
                    callback(data.currentload);
                //console.log(data.currentload);
                //console.log(data.avgload, data.currentload_system);
                data.cpus.map((cpu, i) => {
                    let name = "CPU" + i + 1;
                    let objArray = this.cpumap.get(name);
                    objArray.shift();
                    objArray.push(cpu.load);
                    //if(i == 0)
                    //    console.log(objArray);
                })
            })
            .catch(error => console.error(error))

    }
}

module.exports = new cpu_class();



//钱波 unit test
//var cpu = new cpu_class();
//cpu.say();
//setInterval(() => {
//    cpu.say();
//}, 1000);



//si.cpu()
//    .then(data => {
//        console.log('CPU Information:');
//        console.log('- manufucturer: ' + data.manufacturer);
//        console.log('- brand: ' + data.brand);
//        console.log('- speed: ' + data.speed);
//        console.log('- cores: ' + data.cores);
//        console.log('- physical cores: ' + data.physicalCores);
//        console.log('...');
//    })
//    .catch(error => console.error(error));

内存

var si = require('systeminformation'),
    utils = require('./utils');

var mem_Count;
var mem_Swap;

class mem_class {
    say(callback) {
        si.mem()
            .then(data => {
                var memPer = (100 * (1 - data.available / data.total)).toFixed();
                var swapPer = (100 * (1 - data.swapfree / data.swaptotal)).toFixed();

                swapPer = isNaN(swapPer) ? 0 : swapPer;


                var memTitle =
                    utils.humanFileSize(data.total - data.available) +
                    ' of ' +
                    utils.humanFileSize(data.total);

                var swapTitle =
                    utils.humanFileSize(data.swaptotal - data.swapfree) +
                    ' of ' +
                    utils.humanFileSize(data.swaptotal);

                mem_Count = {
                    percent: memPer / 100,
                    label: memTitle,
                };
                mem_Swap = {
                    percent: swapPer / 100,
                    label: swapTitle
                }

                console.log(mem_Count, mem_Swap);
            })
            .catch(error => console.error(error))

    }
}
module.exports = new mem_class();


/**
 * 单元测试
 * @param {any} data
 */
//function call(data) {
//    console.log(data);
//    //console.log("test");
//}

//var mem = new mem_class();
//mem.say(call);

//module.exports = Mem;

所有连接

// JavaScript source code
var si = require('systeminformation');
const proc = require('./proc_0');


class connection {


    //procdata 进程信息
    say(callback) {
        //this.callback = callback;
        proc.say(function (procdata) {
            si.networkConnections()
                .then(data => {
                    var pu = [];
                    data.map((net, i) => {
                        if (net.state == 'LISTEN') {
                            // console.log(net);
                            //console.log("net pid", net.pid);
                            //console.log("get pid name",proc.getpidname('"'+net.pid+'"'));
                            let name = proc.getpidname('"' + net.pid + '"');
                            //console.log(name);
                            if (name != null) {
                                net.procname = name;
                            }
                            pu.push(net);
                            //console.log(net);
                        }
                    });
                    if (callback != null) {
                        callback(pu);
                        //console.log("pu", pu);
                    }
                })
                .catch(error => console.error(error));

        });
    }
}

module.exports = new connection();

/*
 * unit test
//包含连接信息和连接的进程名称
function callback(data) {
    console.log(data);
}

var x = new connection();
x.say(callback);
*/

你可能感兴趣的:(操作系统,nodejs,http协议,nodejs,cpu,mem,disk,network)