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

后端 未结 6 1140
一个人的身影
一个人的身影 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 21:43

    Another improvement to @musatin solution is to use a self-invoking switch statement instead of reassigning 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);
          });
      }
    

    cmd will 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).

提交回复
热议问题