index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const path = require('path');
  3. const childProcess = require('child_process');
  4. const tasklist = require('tasklist');
  5. const pify = require('pify');
  6. const TEN_MEGABYTE = 1000 * 1000 * 10;
  7. function win() {
  8. return tasklist().then(data => {
  9. return data.map(x => {
  10. return {
  11. pid: x.pid,
  12. name: x.imageName,
  13. cmd: x.imageName
  14. };
  15. });
  16. });
  17. }
  18. function def(opts) {
  19. opts = opts || {};
  20. const ret = {};
  21. const flags = (opts.all === false ? '' : 'a') + 'wwxo';
  22. return Promise.all(['comm', 'args', '%cpu', '%mem'].map(cmd => {
  23. return pify(childProcess.execFile)('ps', [flags, `pid,${cmd}`], {
  24. maxBuffer: TEN_MEGABYTE
  25. }).then(stdout => {
  26. for (let line of stdout.trim().split('\n').slice(1)) {
  27. line = line.trim();
  28. const pid = line.split(' ', 1)[0];
  29. const val = line.slice(pid.length + 1).trim();
  30. if (ret[pid] === undefined) {
  31. ret[pid] = {};
  32. }
  33. ret[pid][cmd] = val;
  34. }
  35. });
  36. })).then(() => {
  37. // Filter out inconsistencies as there might be race
  38. // issues due to differences in `ps` between the spawns
  39. return Object.keys(ret).filter(x => ret[x].comm && ret[x].args).map(x => {
  40. return {
  41. pid: parseInt(x, 10),
  42. name: path.basename(ret[x].comm),
  43. cmd: ret[x].args,
  44. cpu: ret[x]['%cpu'],
  45. memory: ret[x]['%mem']
  46. };
  47. });
  48. });
  49. }
  50. module.exports = process.platform === 'win32' ? win : def;