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

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

    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.

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

提交回复
热议问题