bin.js 892 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict'
  2. const spawn = require('child_process').spawn
  3. /**
  4. * Spawn a binary and read its stdout.
  5. * @param {String} cmd
  6. * @param {String[]} args
  7. * @param {Function} done(err, stdout)
  8. */
  9. function run (cmd, args, options, done) {
  10. if (typeof options === 'function') {
  11. done = options
  12. options = undefined
  13. }
  14. let executed = false
  15. const ch = spawn(cmd, args, options)
  16. let stdout = ''
  17. let stderr = ''
  18. ch.stdout.on('data', function (d) {
  19. stdout += d.toString()
  20. })
  21. ch.stderr.on('data', function (d) {
  22. stderr += d.toString()
  23. })
  24. ch.on('error', function (err) {
  25. if (executed) return
  26. executed = true
  27. done(new Error(err))
  28. })
  29. ch.on('close', function (code, signal) {
  30. if (executed) return
  31. executed = true
  32. if (stderr) {
  33. return done(new Error(stderr))
  34. }
  35. done(null, stdout, code)
  36. })
  37. }
  38. module.exports = run