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
Here's another version of the other answers, with TypeScript and promises:
export async function isProcessRunning(processName: string): Promise<boolean> {
const cmd = (() => {
switch (process.platform) {
case 'win32': return `tasklist`
case 'darwin': return `ps -ax | grep ${processName}`
case 'linux': return `ps -A`
default: return false
}
})()
return new Promise((resolve, reject) => {
require('child_process').exec(cmd, (err: Error, stdout: string, stderr: string) => {
if (err) reject(err)
resolve(stdout.toLowerCase().indexOf(processName.toLowerCase()) > -1)
})
})
}
const running: boolean = await isProcessRunning('myProcess')
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).
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
})
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))
For the related subject, here are some of the best packages:
find-process (The one that I found interesting for my needs)
ps-node
process-exists
Search by name
const processesList = await findProcess(
'name',
/.*?\/kidoAgent\/Broker\/process.js.*/ // regex pattern
);
console.log({ processesList });
if (processesList.length === 0) {
/**
* No process
* (create it)
*/
// ......
}
It return a list of found processes as array!
When running, for the console.log({ processesList });
it show:
{
processesList: [
{
pid: 7415,
ppid: 2451,
uid: 1000,
gid: 1000,
name: 'node',
bin: '/opt/node-v12.4.0-linux-x64/bin/node',
cmd: '/opt/node-v12.4.0-linux-x64/bin/node ' +
'/home/coderhero/Dev/.../build/.../kidoAgent/Broker/process.js'
}
]
}
Check the module for all the options and ways!