Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

node.js - NODEJS process info

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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('
');
    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.');
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...