Node.js以百分比形式获得实际内存使用量

Jor*_*tad 10 javascript linux node.js

我使用过"os" http://nodejs.org/api/os.html#os_os尝试计算一些在应用程序中使用的系统统计信息.

但是我注意到它实际上无法正确计算内存,因为它会省略缓存并且需要缓冲区来正确计算单个可读百分比.没有它,大多数高性能服务器(基于我的测试)的内存几乎总是90%以上.

我需要像这样计算它:

(CURRENT_MEMORY-CACHED_MEMORY-BUFFER_MEMORY)*100/TOTAL_MEMORY

这应该让我获得系统使用的更准确的内存百分比.但是我看到的os模块和大多数其他node.js模块只能得到总的和当前的内存.

有没有办法在node.js中这样做?我可以使用Linux,但我不知道系统的来龙去脉,知道在哪里可以自己解决这个问题(文件读取以获取此信息,如top/htop).

hac*_*ack 5

基于确定 Linux上的空闲内存,空闲内存 = 空闲 + 缓冲区 + 缓存。

以下示例包括从用于比较的节点操作系统方法派生的值(无用)

var spawn = require("child_process").spawn;
var prc = spawn("free", []);
var os = require("os");

prc.stdout.setEncoding("utf8");
prc.stdout.on("data", function (data) {
    var lines = data.toString().split(/\n/g),
        line = lines[1].split(/\s+/),
        total = parseInt(line[1], 10),
        free = parseInt(line[3], 10),
        buffers = parseInt(line[5], 10),
        cached = parseInt(line[6], 10),
        actualFree = free + buffers + cached,
        memory = {
            total: total,
            used: parseInt(line[2], 10),
            free: free,
            shared: parseInt(line[4], 10),
            buffers: buffers,
            cached: cached,
            actualFree: actualFree,
            percentUsed: parseFloat(((1 - (actualFree / total)) * 100).toFixed(2)),
            comparePercentUsed: ((1 - (os.freemem() / os.totalmem())) * 100).toFixed(2)
        };
    console.log("memory", memory);
});

prc.on("error", function (error) {
    console.log("[ERROR] Free memory process", error);
});
Run Code Online (Sandbox Code Playgroud)

感谢 leorex。

检查 process.platform === "linux"


leo*_*rex 4

通过阅读文档,我担心您没有任何本机解决方案。但是,您始终可以直接从命令行调用“free”。我根据 Is it possible to execute an external program from inside node.js?组合了以下代码

var spawn = require('child_process').spawn;
var prc = spawn('free',  []);

prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
  var str = data.toString()
  var lines = str.split(/\n/g);
  for(var i = 0; i < lines.length; i++) {
     lines[i] = lines[i].split(/\s+/);
  }
  console.log('your real memory usage is', lines[2][3]);
});

prc.on('close', function (code) {
    console.log('process exit code ' + code);
});
Run Code Online (Sandbox Code Playgroud)