spawn.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const utils = require('./utils');
  2. const merge = utils.merge;
  3. const bus = utils.bus;
  4. const spawn = require('child_process').spawn;
  5. module.exports = function spawnCommand(command, config, eventArgs) {
  6. var stdio = ['pipe', 'pipe', 'pipe'];
  7. if (config.options.stdout) {
  8. stdio = ['pipe', process.stdout, process.stderr];
  9. }
  10. var sh = 'sh';
  11. var shFlag = '-c';
  12. if (utils.isWindows) {
  13. sh = 'cmd';
  14. shFlag = '/c';
  15. }
  16. if (!Array.isArray(command)) {
  17. command = [command];
  18. }
  19. const args = command.join(' ');
  20. const env = merge(process.env, { FILENAME: eventArgs[0] });
  21. const child = spawn(sh, [shFlag, args], {
  22. env: merge(config.options.execOptions.env, env),
  23. stdio: stdio,
  24. });
  25. if (config.required) {
  26. var emit = {
  27. stdout: function (data) {
  28. bus.emit('stdout', data);
  29. },
  30. stderr: function (data) {
  31. bus.emit('stderr', data);
  32. },
  33. };
  34. // now work out what to bind to...
  35. if (config.options.stdout) {
  36. child.on('stdout', emit.stdout).on('stderr', emit.stderr);
  37. } else {
  38. child.stdout.on('data', emit.stdout);
  39. child.stderr.on('data', emit.stderr);
  40. bus.stdout = child.stdout;
  41. bus.stderr = child.stderr;
  42. }
  43. }
  44. };