使用NodeJS获取内存和处理器使用率

时间:2018-10-10 10:56:18

标签: node.js

我想使用NodeJS获取内存使用率,并使用Web页面显示值。

我已使用以下代码,并在控制台中成功获取结果数组值。

setInterval(function () {
    var result = [];
    var current = _.map(os.cpus(), function (cpu) { return cpu.times; })
    _.each(current, function (item, cpuKey) {
        result[cpuKey] = {}

        var oldVal = old[cpuKey];
        _.each(_.keys(item), function (timeKey) {
            var diff = (parseFloat((item[timeKey]) - parseFloat(oldVal[timeKey])) / parseFloat((interval * 100)));
            var name = timeKey;
            if (timeKey == "idle") {
                name = "CPU"
                diff = 100 - diff;
            }
            result[cpuKey][name] = diff.toFixed(0);
        });
    });
    router.get('/', (req, res) => {
        res.status(200).json(result);
    });
    old = current;
}, (interval * 1000));

但是当我使用下面的请求代码时,它只给出结果数据数组的一个值。

setInterval(function () {
    var result = [];
    var current = _.map(os.cpus(), function (cpu) { return cpu.times; })
    _.each(current, function (item, cpuKey) {
        result[cpuKey] = {}

        var oldVal = old[cpuKey];
        _.each(_.keys(item), function (timeKey) {
            var diff = (parseFloat((item[timeKey]) - parseFloat(oldVal[timeKey])) / parseFloat((interval * 100)));
            var name = timeKey;
            if (timeKey == "idle") {
                name = "CPU"
                diff = 100 - diff;
            }
            result[cpuKey][name] = diff.toFixed(0);
        });
    });
    router.get('/', (req, res) => {
        res.status(200).json(result);
    });
    old = current;
}, (interval * 1000));

我想获取结果数组的所有值。

0 个答案:

没有答案