exec-sh.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var cp = require('child_process')
  2. var merge = require('merge')
  3. var defSpawnOptions = { stdio: 'inherit' }
  4. /**
  5. * @summary Get shell program meta for current platform
  6. * @private
  7. * @returns {Object}
  8. */
  9. function getShell () {
  10. if (process.platform === 'win32') {
  11. return { cmd: 'cmd', arg: '/C' }
  12. } else {
  13. return { cmd: 'sh', arg: '-c' }
  14. }
  15. }
  16. /**
  17. * Callback is called with the output when the process terminates. Output is
  18. * available when true is passed as options argument or stdio: null set
  19. * within given options.
  20. *
  21. * @summary Execute shell command forwarding all stdio
  22. * @param {String|Array} command
  23. * @param {Object|TRUE} [options] spawn() options or TRUE to set stdio: null
  24. * @param {Function} [callback]
  25. * @returns {ChildProcess}
  26. */
  27. function execSh (command, options, callback) {
  28. if (Array.isArray(command)) {
  29. command = command.join(';')
  30. }
  31. if (options === true) {
  32. options = { stdio: null }
  33. }
  34. if (typeof options === 'function') {
  35. callback = options
  36. options = defSpawnOptions
  37. } else {
  38. options = options || {}
  39. options = merge(true, defSpawnOptions, options)
  40. callback = callback || function () {}
  41. }
  42. var child
  43. var stdout = ''
  44. var stderr = ''
  45. var shell = getShell()
  46. try {
  47. child = cp.spawn(shell.cmd, [shell.arg, command], options)
  48. } catch (e) {
  49. callback(e, stdout, stderr)
  50. return
  51. }
  52. if (child.stdout) {
  53. child.stdout.on('data', function (data) {
  54. stdout += data
  55. })
  56. }
  57. if (child.stderr) {
  58. child.stderr.on('data', function (data) {
  59. stderr += data
  60. })
  61. }
  62. child.on('close', function (code) {
  63. if (code) {
  64. var e = new Error('Shell command exit with non zero code: ' + code)
  65. e.code = code
  66. callback(e, stdout, stderr)
  67. } else {
  68. callback(null, stdout, stderr)
  69. }
  70. })
  71. return child
  72. }
  73. module.exports = execSh