node.js 如何通过进程名称检查进程是否正在运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38033127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:20:37  来源:igfitidea点击:

node.js how to check a process is running by the process name?

node.js

提问by user3552178

i run node.js in linux, from node.js how to check if a process is running from the process name ? Worst case i use child_process, but wonder if better ways ?

我在 linux 中运行 node.js,从 node.js 如何检查进程是否从进程名称运行?最坏的情况是我使用 child_process,但想知道是否有更好的方法?

Thanks !

谢谢 !

采纳答案by Samuel Toh

You can use the ps-node package.

您可以使用 ps-node 包。

https://www.npmjs.com/package/ps-node

https://www.npmjs.com/package/ps-node

var ps = require('ps-node');

// A simple pid lookup 
ps.lookup({
    command: 'node',
    psargs: 'ux'
    }, function(err, resultList ) {
    if (err) {
        throw new Error( err );
    }

    resultList.forEach(function( process ){
        if( process ){
            console.log( 'PID: %s, COMMAND: %s, ARGUMENTS: %s', process.pid, process.command, process.arguments );
        }
    });
});

I believe you'll be looking at this example. Check out the site, they have plenty of other usages. Give it a try.

我相信你会看到这个例子。查看该站点,它们还有很多其他用途。试一试。

Just incase you are not bound to nodejs, from linux command line you can also do ps -ef | grep "YOUR_PROCESS_NAME_e.g._nodejs"to check for a running process.

以防万一您没有绑定到 nodejs,您还可以从 linux 命令行ps -ef | grep "YOUR_PROCESS_NAME_e.g._nodejs"检查正在运行的进程。

回答by d_scalzi

The following should work. A process list will be generated based on the operating system and that output will be parsed for the desired program. The function takes three arguments, each is just the expected process name on the corresponding operating system.

以下应该工作。将根据操作系统生成进程列表,并将为所需程序解析该输出。该函数接受三个参数,每个参数只是相应操作系统上的预期进程名称。

In my experience ps-node takes WAY too much memory and time to search for the process. This solution is better if you plan on frequently checking for processes.

根据我的经验,ps-node 需要太多的内存和时间来搜索进程。如果您计划经常检查进程,则此解决方案会更好。

const exec = require('child_process').exec

function isRunning(win, mac, linux){
    return new Promise(function(resolve, reject){
        const plat = process.platform
        const cmd = plat == 'win32' ? 'tasklist' : (plat == 'darwin' ? 'ps -ax | grep ' + mac : (plat == 'linux' ? 'ps -A' : ''))
        const proc = plat == 'win32' ? win : (plat == 'darwin' ? mac : (plat == 'linux' ? linux : ''))
        if(cmd === '' || proc === ''){
            resolve(false)
        }
        exec(cmd, function(err, stdout, stderr) {
            resolve(stdout.toLowerCase().indexOf(proc.toLowerCase()) > -1)
        })
    })
}

isRunning('myprocess.exe', 'myprocess', 'myprocess').then((v) => console.log(v))

回答by musatin

A little improvement of code answered by d_scalzi. Function with callback instead of promises, with only one variable query and with switch instead of if/else.

d_scalzi回答的代码的一些改进。带有回调而不是承诺的函数,只有一个变量查询和开关而不是 if/else。

const exec = require('child_process').exec;

const isRunning = (query, cb) => {
    let platform = process.platform;
    let cmd = '';
    switch (platform) {
        case 'win32' : cmd = `tasklist`; break;
        case 'darwin' : cmd = `ps -ax | grep ${query}`; break;
        case 'linux' : cmd = `ps -A`; break;
        default: break;
    }
    exec(cmd, (err, stdout, stderr) => {
        cb(stdout.toLowerCase().indexOf(query.toLowerCase()) > -1);
    });
}

isRunning('chrome.exe', (status) => {
    console.log(status); // true|false
})

回答by Christiaan Maks

Here's another version of the other answers, with TypeScript and promises:

这是其他答案的另一个版本,带有 TypeScript 和 promise:

export async function isProcessRunning(processName: string): Promise<boolean> {
  const cmd = (() => {
    switch (process.platform) {
      case 'win32': return `tasklist`
      case 'darwin': return `ps -ax | grep ${processName}`
      case 'linux': return `ps -A`
      default: return false
    }
  })()

  return new Promise((resolve, reject) => {
    require('child_process').exec(cmd, (err: Error, stdout: string, stderr: string) => {
      if (err) reject(err)

      resolve(stdout.toLowerCase().indexOf(processName.toLowerCase()) > -1)
    })
  })
}
const running: boolean = await isProcessRunning('myProcess')

回答by Scott P

Another improvement to @musatin solution is to use a self-invoking switch statement instead of reassigning let;

@musatin 解决方案的另一个改进是使用自调用 switch 语句而不是重新分配let

/**
 * 
 * @param {string} processName The executable name to check
 * @param {function} cb The callback function
 * @returns {boolean} True: Process running, else false
 */
  isProcessRunning(processName, cb){
      const cmd = (()=>{
          switch (process.platform) {
              case 'win32' : return `tasklist`;
              case 'darwin' : return `ps -ax | grep ${processName}`;
              case 'linux' : return `ps -A`;
              default: return false;
          }
      })();
      require('child_process').exec(cmd, (err, stdout, stderr) => {
          cb(stdout.toLowerCase().indexOf(processName.toLowerCase()) > -1);
      });
  }

cmdwill be assigned the result of the switch statement and results in code that's easier to read (especially if more complex code is involved, self-invoking switch statements means you only create the variables you need and don't need to mentally keep track of what their values might be).

cmd将被分配 switch 语句的结果并生成更易于阅读的代码(特别是如果涉及更复杂的代码,自调用 switch 语句意味着您只需创建您需要的变量,而无需在头脑中跟踪什么他们的价值可能是)。