stats.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict'
  2. const fs = require('fs')
  3. const os = require('os')
  4. const platformToMethod = {
  5. aix: 'ps',
  6. android: 'procfile',
  7. alpine: 'procfile',
  8. darwin: 'ps',
  9. freebsd: 'ps',
  10. os390: 'ps',
  11. linux: 'procfile',
  12. netbsd: 'procfile',
  13. sunos: 'ps',
  14. win: 'wmic'
  15. }
  16. const ps = require('./ps')
  17. let platform = os.platform()
  18. if (fs.existsSync('/etc/alpine-release')) {
  19. platform = 'alpine'
  20. }
  21. if (platform.match(/^win/)) {
  22. platform = 'win'
  23. }
  24. let stat
  25. try {
  26. stat = require('./' + platformToMethod[platform])
  27. } catch (err) {}
  28. /**
  29. * @callback pidCallback
  30. * @param {Error} err A possible error.
  31. * @param {Object} statistics The object containing the statistics.
  32. */
  33. /**
  34. * Get pid informations.
  35. * @public
  36. * @param {Number|Number[]|String|String[]} pids A pid or a list of pids.
  37. * @param {Object} [options={}] Options object
  38. * @param {pidCallback} callback Called when the statistics are ready.
  39. */
  40. function get (pids, options, callback) {
  41. let fn = stat
  42. if (platform !== 'win' && options.usePs === true) {
  43. fn = ps
  44. }
  45. if (stat === undefined) {
  46. return callback(new Error(os.platform() + ' is not supported yet, please open an issue (https://github.com/soyuka/pidusage)'))
  47. }
  48. let single = false
  49. if (!Array.isArray(pids)) {
  50. single = true
  51. pids = [pids]
  52. }
  53. if (pids.length === 0) {
  54. return callback(new TypeError('You must provide at least one pid'))
  55. }
  56. for (let i = 0; i < pids.length; i++) {
  57. pids[i] = parseInt(pids[i], 10)
  58. if (isNaN(pids[i]) || pids[i] < 0) {
  59. return callback(new TypeError('One of the pids provided is invalid'))
  60. }
  61. }
  62. fn(pids, options, function (err, stats) {
  63. if (err) {
  64. return callback(err)
  65. }
  66. if (single) {
  67. callback(null, stats[pids[0]])
  68. } else {
  69. callback(null, stats)
  70. }
  71. })
  72. }
  73. module.exports = get