[英]node.js how to check a process is running by the process name?
我在 linux 中運行 node.js,從 node.js 如何檢查進程是否從進程名稱運行? 最壞的情況是我使用 child_process,但想知道是否有更好的方法?
謝謝!
您可以使用 ps-node 包。
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 );
}
});
});
我相信你會看到這個例子。 查看該站點,它們還有很多其他用途。 試一試。
以防萬一你沒有綁定到 nodejs,你也可以從 linux 命令行執行ps -ef | grep "YOUR_PROCESS_NAME_e.g._nodejs"
ps -ef | grep "YOUR_PROCESS_NAME_e.g._nodejs"
來檢查正在運行的進程。
d_scalzi回答的代碼的一些改進。 帶有回調而不是承諾的函數,只有一個變量查詢和開關而不是 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
})
以下應該工作。 將根據操作系統生成進程列表,並將為所需程序解析該輸出。 該函數接受三個參數,每個參數只是相應操作系統上的預期進程名稱。
根據我的經驗,ps-node 需要太多的內存和時間來搜索進程。 如果您計划經常檢查進程,則此解決方案會更好。
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))
這是其他答案的另一個版本,帶有 TypeScript 和 promise:
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')
對於相關主題,這里有一些最好的軟件包:
find-process (我發現對我的需求很有趣的那個)
按名稱搜索
const processesList = await findProcess(
'name',
/.*?\/kidoAgent\/Broker\/process.js.*/ // regex pattern
);
console.log({ processesList });
if (processesList.length === 0) {
/**
* No process
* (create it)
*/
// ......
}
它將找到的進程列表作為數組返回!
運行時,為console.log({ processesList });
它顯示:
{
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'
}
]
}
檢查模塊的所有選項和方法!
@musatin 解決方案的另一個改進是使用自調用 switch 語句而不是重新分配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
將被分配 switch 語句的結果,並生成更易於閱讀的代碼(特別是如果涉及更復雜的代碼,自調用 switch 語句意味着您只需創建您需要的變量,而無需在精神上跟蹤他們的價值可能是什么)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.