helper.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. const runScript = require('runscript');
  3. const isWin = process.platform === 'win32';
  4. const REGEX = isWin ? /^(.*)\s+(\d+)\s*$/ : /^\s*(\d+)\s+(.*)/;
  5. exports.findNodeProcess = function* (filterFn) {
  6. const command = isWin ?
  7. 'wmic Path win32_process Where "Name = \'node.exe\'" Get CommandLine,ProcessId' :
  8. // command, cmd are alias of args, not POSIX standard, so we use args
  9. 'ps -wweo "pid,args"';
  10. const stdio = yield runScript(command, { stdio: 'pipe' });
  11. const processList = stdio.stdout.toString().split('\n')
  12. .reduce((arr, line) => {
  13. if (!!line && !line.includes('/bin/sh') && line.includes('node')) {
  14. const m = line.match(REGEX);
  15. /* istanbul ignore else */
  16. if (m) {
  17. const item = isWin ? { pid: m[2], cmd: m[1] } : { pid: m[1], cmd: m[2] };
  18. if (!filterFn || filterFn(item)) {
  19. arr.push(item);
  20. }
  21. }
  22. }
  23. return arr;
  24. }, []);
  25. return processList;
  26. };
  27. exports.kill = function(pids, signal) {
  28. pids.forEach(pid => {
  29. try {
  30. process.kill(pid, signal);
  31. } catch (err) { /* istanbul ignore next */
  32. if (err.code !== 'ESRCH') {
  33. throw err;
  34. }
  35. }
  36. });
  37. };