NODEJS流程信息

pia*_*829 35 process node.js

如何PID在Node.JS程序中获得具有(进程ID)的进程名称,平台包括Mac,Windows,Linux.

它有一些节点模块吗?

Amo*_*rni 46

是的,内置/核心模块可以process做到这一点:

所以,只说var process = require('process');那么

获取PID(进程ID):

if (process.pid) {
  console.log('This process is your pid ' + process.pid);
}
Run Code Online (Sandbox Code Playgroud)

获取平台信息:

console.log('This platform is ' + process.platform);
Run Code Online (Sandbox Code Playgroud)

注意:您只能了解子进程或父进程的PID.


根据您的要求更新.(已测试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)));
         }
        }) 
    });
});
Run Code Online (Sandbox Code Playgroud)

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.');
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 您不需要 require("process"),它是一个已经可用的全局变量。https://nodejs.org/api/process.html#process_process (2认同)

Vij*_*wat 12

在Ubuntu Linux上,我尝试过

var process = require('process'); but it gave error.
Run Code Online (Sandbox Code Playgroud)

我试过没有导入它工作的任何过程模块

console.log('This process is your pid ' + process.pid);
Run Code Online (Sandbox Code Playgroud)

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

process.title = 'node-chat' 
Run Code Online (Sandbox Code Playgroud)

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

ps -aux | grep node-chat
Run Code Online (Sandbox Code Playgroud)


Did*_*r68 5

参见官方文档 https://nodejs.org/dist/latest-v10.x/docs/api/process.html#process_process_pid

要求是没有更多的需要。好的样本是:

 console.log(`This process is pid ${process.pid}`); 
Run Code Online (Sandbox Code Playgroud)