spawn.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const path = require('path');
  2. const utils = require('./utils');
  3. const merge = utils.merge;
  4. const bus = utils.bus;
  5. const spawn = require('child_process').spawn;
  6. module.exports = function spawnCommand(command, config, eventArgs) {
  7. var stdio = ['pipe', 'pipe', 'pipe'];
  8. if (config.options.stdout) {
  9. stdio = ['pipe', process.stdout, process.stderr];
  10. }
  11. const env = merge(process.env, { FILENAME: eventArgs[0] });
  12. var sh = 'sh';
  13. var shFlag = '-c';
  14. var spawnOptions = {
  15. env: merge(config.options.execOptions.env, env),
  16. stdio: stdio,
  17. };
  18. if (!Array.isArray(command)) {
  19. command = [command];
  20. }
  21. if (utils.isWindows) {
  22. // if the exec includes a forward slash, reverse it for windows compat
  23. // but *only* apply to the first command, and none of the arguments.
  24. // ref #1251 and #1236
  25. command = command.map(executable => {
  26. if (executable.indexOf('/') === -1) {
  27. return executable;
  28. }
  29. return executable.split(' ').map((e, i) => {
  30. if (i === 0) {
  31. return path.normalize(e);
  32. }
  33. return e;
  34. }).join(' ');
  35. });
  36. // taken from npm's cli: https://git.io/vNFD4
  37. sh = process.env.comspec || 'cmd';
  38. shFlag = '/d /s /c';
  39. spawnOptions.windowsVerbatimArguments = true;
  40. }
  41. const args = command.join(' ');
  42. const child = spawn(sh, [shFlag, args], spawnOptions);
  43. if (config.required) {
  44. var emit = {
  45. stdout: function (data) {
  46. bus.emit('stdout', data);
  47. },
  48. stderr: function (data) {
  49. bus.emit('stderr', data);
  50. },
  51. };
  52. // now work out what to bind to...
  53. if (config.options.stdout) {
  54. child.on('stdout', emit.stdout).on('stderr', emit.stderr);
  55. } else {
  56. child.stdout.on('data', emit.stdout);
  57. child.stderr.on('data', emit.stderr);
  58. bus.stdout = child.stdout;
  59. bus.stderr = child.stderr;
  60. }
  61. }
  62. };