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 !
You can use the ps-node package.
https://www.npmjs.com/package/ps-node
var ps = require('ps-node'); // A simple pid lookup ps.lookup({ command: 'node', psargs: 'ux' }, function(err, resultList ) { if (err) { throw new Error( err ); } resultList.forEach(function( process ){ if( process ){ console.log( 'PID: %s, COMMAND: %s, ARGUMENTS: %s', process.pid, process.command, process.arguments ); } }); });
I believe you'll be looking at this example. Check out the site, they have plenty of other usages. Give it a try.
Just incase you are not bound to nodejs, from linux command line you can also do ps -ef | grep "YOUR_PROCESS_NAME_e.g._nodejs"
to check for a running process.
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With