如何在 node 中获取进程名称和PID(进程ID).JS程序,平台包括Mac、Windows、Linux.

它是否有一些 node 模块来完成这项工作?

推荐答案

是的,内置/核心模块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);

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


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

Linux岁时,你可以try 以下方式:

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

Node.js相关问答推荐

无法在我的 node 项目中转让Google Drive v3 API中的所有权

GraphQL MongoDB Mongoose填充字段未获取多个类别

Socket.io 未将用户加入给定房间

为什么我的过滤器无法在我在下面编写的 Google Analytics 4 应用程序脚本代码中工作?我该如何修复它?

如何在docker容器上正确安装nodejs?

如何从 Mongo Atlas 触发器向 GCP PubSub 发出经过身份验证的请求

2023年如何在Node.js中使用Gmail发送邮箱?

如何修复我的 NodeJS SSE 写入函数以在后续调用中更新 HTML?

Mongoose post中间件触发deleteMany

Angular Build 生产返回致命的 javascript 无效大小错误

Node.js |如何在微服务之间转发标头?

在 node:readline 中按 CTRL+D 时会发出什么信号?

如何为一个网站实现这 2 个网址.即 www.administrator.sitename.com 和 www.sitename.com?

Firestore promise 在退货前等待产品详细信息

Node js中向rest服务发送https请求的步骤

搜索MongoDB条目的正确方法是'_id';在 node 中

运行摩卡+伊斯坦布尔+通天塔

Javascript在try块内设置const变量

Node.js 连接仅适用于本地主机

yarn 和 npm 的主要区别是什么?