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