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

后端 未结 6 1095
一个人的身影
一个人的身影 2021-01-03 20:58

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 ?

Thanks

6条回答
  •  星月不相逢
    2021-01-03 21:42

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

    export async function isProcessRunning(processName: string): Promise {
      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')
    

提交回复
热议问题