簡體   English   中英

Node.js是否創建一個模塊來收集內存(RAM)信息?

[英]Node.js creating a module to gather memory (ram) info?

我想做的是在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("\r\n")[1].toString()) / 1073741824; // 1024^3
  });

  exec("wmic OS get FreePhysicalMemory", function (error, stdout, stderr) {
    mem_avail = parseInt(stdout.split("\r\n")[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("\r\n")[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("\r\n")[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("\r\n")[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("\r\n")[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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM