61

How to get the process name with a PID (Process ID) in Node.JS program, platform include Mac, Windows, Linux.

Does it has some node modules to do it?

pianist829
  • 613
  • 1
  • 5
  • 5

3 Answers3

79

Yes, built-in/core modules process does this:

So, just say var process = require('process'); Then

To get PID (Process ID):

if (process.pid) {
  console.log('This process is your pid ' + process.pid);
}

To get Platform information:

console.log('This platform is ' + process.platform);

Note: You can only get to know the PID of child process or parent process.


Updated as per your requirements. (Tested On WINDOWS)
var exec = require('child_process').exec;
var yourPID = '1444';

exec('tasklist', function(err, stdout, stderr) { 
    var lines = stdout.toString().split('\n');
    var results = new Array();
    lines.forEach(function(line) {
        var parts = line.split('=');
        parts.forEach(function(items){
        if(items.toString().indexOf(yourPID) > -1){
        console.log(items.toString().substring(0, items.toString().indexOf(yourPID)));
         }
        }) 
    });
});

On Linux you can try something like:

var spawn = require('child_process').spawn,
    cmdd = spawn('your_command'); //something like: 'man ps'

cmdd.stdout.on('data', function (data) {
  console.log('' + data);
});
cmdd.stderr.setEncoding('utf8');
cmdd.stderr.on('data', function (data) {
  if (/^execvp\(\)/.test(data)) {
    console.log('Failed to start child process.');
  }
});
Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164
  • 1
    To get `PID` you should use `process.pid`, but not `process.getgid`. – zavg Jul 15 '13 at 16:40
  • 4
    You're not required to require("process"), it's a global variable already avaiable. https://nodejs.org/api/process.html#process_process – maxgalbu Dec 03 '20 at 13:54
  • use ==> if (items.toString().search('\\b' + yourPID + '\\b') > -1) instead of if(items.toString().indexOf(yourPID) > -1). Because this give true if the 'yourPID' is match in the item other than PID ( eg: it will be true if that is match in memory slot) – user2609021 Jan 08 '21 at 11:07
14

On Ubuntu Linux, I tried

var process = require('process'); but it gave error.

I tried without importing any process module it worked

console.log('This process is your pid ' + process.pid);

One more thing I noticed we can define name for the process using

process.title = 'node-chat' 

To check the nodejs process in bash shell using following command

ps -aux | grep node-chat
Vijay Rawat
  • 241
  • 2
  • 7
8

cf official documentation https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid

the require is no more needed. The good sample is :

 console.log(`This process is pid ${process.pid}`); 
Didier68
  • 1,027
  • 12
  • 26