NODEJS进程信息

如何在Node.JS程序中使用PID (Process ID)获取进程名称,平台包括Mac,Windows,Linux。

它是否有一些节点模块来做到这一点?

是的,内置/核心模块的process是这样的:

所以,只要说var process = require('process'); 然后

获得PID(进程ID):

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

获取平台信息:

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

注意:您只能了解subprocess或父进程的PID。


根据您的要求更新。 (在WINDOWStesting)

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

Linux您可以尝试如下所示:

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

在Ubuntu Linux上,我试过了

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

我尝试不导入任何工作模块

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

还有一件事我注意到,我们可以使用过程定义名称

 process.title = 'node-chat' 

使用以下命令检查bash shell中的nodejs进程

 ps -aux | grep node-chat