类unix系统的解决方案:
const child_process = require('child_process');
const displayProcessBy = (pattern) => {
let command = `ps -aux | grep ${pattern}`;
child_process.exec(command, (err, stdout, stdin) => {
if (err) throw err;
console.log(stdout);
});
}
示例用法和结果
displayProcessBy("nodejs");
setivol+ 7912 0.0 0.0 12732 2108 ? S 10:56 0:00 grep nodejs
setivol+ 12427 0.0 0.0 669552 712 pts/3 Tl Dec16 0:00 nodejs
setivol+ 14400 0.0 0.0 669552 644 pts/2 Tl Dec15 0:00 nodejs
setivol+ 14412 0.0 0.0 670576 224 pts/3 Tl Dec16 0:00 nodejs
setivol+ 14567 0.0 0.0 669552 436 pts/3 Tl Dec15 0:00 nodejs
setivol+ 14911 0.0 0.0 669552 0 pts/3 Tl Dec15 0:00 nodejs
setivol+ 15489 0.0 0.0 669552 712 pts/3 Tl Dec16 0:00 nodejs
setivol+ 15659 0.0 0.0 669520 0 pts/3 Tl Dec16 0:00 nodejs --harmony
setivol+ 16469 0.0 0.0 669520 704 pts/3 Tl Dec16 0:00 nodejs --harmony
setivol+ 20514 0.0 0.0 669552 664 pts/2 Tl Dec15 0:00 nodejs
displayProcessBy("python2")
setivol+ 8012 0.0 0.0 4336 712 ? S 10:58 0:00 /bin/sh -c ps -aux | grep python2
setivol+ 8014 0.0 0.0 12728 2240 ? S 10:58 0:00 grep python2
测试环境
$ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 8.6 (jessie)
Release: 8.6
Codename: jessie