Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a child process memory usage in node.js?

I know there is a api process.memoryUsage() to get memory usage in current process.

But if I start a new child process by child_process.spawn(command, [args], [options]) and I get a ChildProcess object, then how can I get the new process memory usage?

like image 911
CALL ME TZ Avatar asked May 24 '12 02:05

CALL ME TZ


2 Answers

The easiest way to get child's memoryUsage is installing pidusage

Link: https://www.npmjs.com/package/pidusage

In the console write this to install it:

In Windows Command: npm i pidusage --save
In Mac Command : sudo npm i pidusage --save

let pidusage = require('pidusage');

const cp = require("child_process");

const child = cp.spawn('ls', ['-lh', '/usr']);

pidusage(child.pid, function (err, stats) {

console.log(stats);

});
/*
Output: 
{
   cpu: 10.0,            // percentage (from 0 to 100*vcore)
   memory: 357306368,    // bytes
   ppid: 312,            // PPID
   pid: 727,             // PID
   ctime: 867000,        // ms user + system time
   elapsed: 6650000,     // ms since the start of the process
   timestamp: 864000000  // ms since epoch
}
*/

If you want to get more than one child's memoryUsage you need to change child.pid for and array [child.pid,child2.pid], function (err, stats) ...

like image 71
Juan Sánchez Avatar answered Sep 28 '22 17:09

Juan Sánchez


We can get multiplatform solution with using nodejs ipc protocol. you just need to setup event for requesting memory usage from parent process, and then send process.memoryUsage() from spawned child process.

parent.js

var ChildProcess = require('child_process'),
    child = ChildProcess.fork('./child.js');

child.on('message', function(payload){
    console.log(payload.memUsage);
});

child.send('get_mem_usage');

and in child.js it might look like this

process.on('message', function(msg){
    if(msg === 'get_mem_usage'){
         process.send({memUsage: process.memoryUsage()});
    }
});
like image 41
port115 Avatar answered Sep 28 '22 19:09

port115