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

后端 未结 6 1094
一个人的身影
一个人的身影 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:45

    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.

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

提交回复
热议问题