Node.js get actual memory usage as a percentage

I used "os" http://nodejs.org/api/os.html#os_os to try to calculate some system statistics for use in the application.

However, I notice that it cannot correctly calculate the memory properly, since it does not take into account the cache and buffers needed to correctly calculate one readable percentage. Without it, the memory will almost always be 90% + with most high-performance servers (based on my testing).

I would need to compute it like this:

(CURRENT_MEMORY-CACHED_MEMORY-BUFFER_MEMORY) * 100 / TOTAL_MEMORY

This will give me a more accurate% of the memory used by the system. But the os module and most of the other node.js modules I've seen get only full and current memory.

Is there a way to do this in node.js? I can use Linux, but I don’t know on which systems the system knows where to look, to figure it out on its own (a read file to get this information, for example top / htop).

+8
javascript linux
source share
2 answers

From reading the documentation, I'm afraid you don't have your own solution. However, you can always call β€œfree” from the command line directly. I have compiled the following code based on Is it possible to execute an external program from 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); }); 
+4
source share

Based on the definition of free memory in Linux , Free memory = free + buffers + cache.

The following example includes values ​​obtained from node os methods for comparison (which are useless)

 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); }); 

Thanks leorex.

Check for process.platform === "linux"

+3
source share

All Articles