bin.js 1.0 KB

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