Node.js创建一个模块来收集内存(ram)信息



我想做的是在Windows机器上的Node.js中每X秒(在本例中仅为1秒)打印一次本地内存使用情况。具有实际收集数据功能的代码需要在一个单独的模块中。这是我当前的代码:

server.js:中

mem_stats = require("./mem_stats.js");
setInterval(function () {
  mem_stats.update();
  console.log(mem_stats.mem_total);
}, 1000);

mem_stats.js:中

var exec = require("child_process").exec,
  mem_total,
  mem_avail,
  mem_used;
exports.update = function () {
  exec("wmic ComputerSystem get TotalPhysicalMemory", function (error, stdout, stderr) {
    mem_total = parseInt(stdout.split("rn")[1].toString()) / 1073741824; // 1024^3
  });
  exec("wmic OS get FreePhysicalMemory", function (error, stdout, stderr) {
    mem_avail = parseInt(stdout.split("rn")[1]) / 1048576; // 1024^2
  });
}
exports.mem_total = mem_total;
exports.mem_avail = mem_avail;
exports.mem_used = mem_total - mem_avail;

我怀疑(/很确定)这与JS的异步方式有关,但我似乎无法找到绕过它的方法(通过回调等)。我现在已经尝试了很多事情,但无论我做什么,我总是以打印undefined结束。。。

把我的代码改成这样也没有解决任何问题:

function mem_total () {
  var temp;
  exec("wmic ComputerSystem get TotalPhysicalMemory", function (error, stdout, stderr) {
    temp = parseInt(stdout.split("rn")[1].toString()) / 1073741824; // 1024^3
  });
  return temp;
};
function mem_avail () {
  var temp;
  exec("wmic OS get FreePhysicalMemory", function (error, stdout, stderr) {
    temp = parseInt(stdout.split("rn")[1]) / 1048576; // 1024^2
  });
  return temp;
};
exports.mem_total = mem_total();
exports.mem_avail = mem_avail();

我就是不明白。

我知道这个问题可能看起来(相当)有点愚蠢,但我对编写JS没有太多经验,我非常习惯于更多面向C(++)的语言。不过还是谢谢。

对于第二个示例,该命令将以以下方式执行

function mem_total () {
  var temp;
  // call exec now. Since it is async, When the function finishes, 
  // call the callback provided
  exec("wmic ComputerSystem get TotalPhysicalMemory", function (error, stdout, stderr) {
    // temp is modified AFTER mem_total has returned
    temp = parseInt(stdout.split("rn")[1].toString()) / 1073741824; // 1024^3
  });
  // return temp before exec finishes.
  return temp;
};

也许你想要以下内容:

function mem_total (callback) {
  var temp;
  exec("wmic ComputerSystem get TotalPhysicalMemory", function (error, stdout, stderr) {
    // temp is modified AFTER the function has returned
    temp = parseInt(stdout.split("rn")[1].toString()) / 1073741824; // 1024^3
    callback(error, temp);
  });
};

并以以下方式调用函数

mem_total(function(err, mem) {
    if (err) {
        console.log(err);
        return;
    }
    console.log('total memory is ', mem);
});

最新更新