shell.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const child_process_1 = require("child_process");
  4. class ShellError extends Error {
  5. constructor(message) {
  6. message = message && message.split('\n')[0]; // assign only first line
  7. super(message);
  8. }
  9. }
  10. exports.ShellError = ShellError;
  11. function shellAsync(command, options = {}) {
  12. return new Promise((resolve, reject) => {
  13. const nextOptions = Object.assign({}, options, { shell: true, stdio: options.stdio || 'inherit' });
  14. const asyncProcess = child_process_1.spawn(command, nextOptions);
  15. let output = null;
  16. asyncProcess.on('error', (error) => {
  17. reject(new ShellError(`Failed to start command: ${command}; ${error.toString()}`));
  18. });
  19. asyncProcess.on('close', (exitCode) => {
  20. if (exitCode === 0) {
  21. resolve(output);
  22. }
  23. else {
  24. reject(new ShellError(`Command failed: ${command} with exit code ${exitCode}`));
  25. }
  26. });
  27. if (nextOptions.stdio === 'pipe') {
  28. asyncProcess.stdout.on('data', (buffer) => {
  29. output = buffer.toString();
  30. });
  31. }
  32. if (nextOptions.timeout) {
  33. setTimeout(() => {
  34. asyncProcess.kill();
  35. reject(new ShellError(`Command timeout: ${command}`));
  36. }, nextOptions.timeout);
  37. }
  38. });
  39. }
  40. function shellSync(command, options = {}) {
  41. try {
  42. const nextOptions = Object.assign({}, options, { stdio: options.stdio || 'inherit' });
  43. const buffer = child_process_1.execSync(command, nextOptions);
  44. if (buffer) {
  45. return buffer.toString();
  46. }
  47. return null;
  48. }
  49. catch (error) {
  50. throw new ShellError(error.message);
  51. }
  52. }
  53. function shell(command, options) {
  54. return options && options.async
  55. ? shellAsync(command, options)
  56. : shellSync(command, options);
  57. }
  58. exports.default = shell;
  59. //# sourceMappingURL=shell.js.map