process.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const child_process = require('child_process');
  2. let execCommandAsync = function (options) {
  3. if (!options || !options.command || !options.command.trim()) {
  4. return;
  5. }
  6. let finalArguments = [];
  7. if (options.args) {
  8. const argsArr = options.args.split('\n');
  9. for (let i = 0; i < argsArr.length; i++) {
  10. let arg = argsArr[i];
  11. if (!arg) {
  12. continue;
  13. }
  14. arg = arg.replace('\r', '').trim();
  15. if (arg) {
  16. finalArguments.push(arg);
  17. }
  18. }
  19. }
  20. try {
  21. const child = child_process.spawn(options.command, finalArguments, {
  22. encoding: 'utf8',
  23. detached: !!options.detached
  24. });
  25. if (options.onoutput) {
  26. child.stdout.on('data', (data) => {
  27. options.onoutput({
  28. source: 'stdout',
  29. content: data.toString(),
  30. count: 1
  31. });
  32. });
  33. }
  34. if (options.onoutput) {
  35. child.stderr.on('data', (data) => {
  36. options.onoutput({
  37. source: 'stderr',
  38. content: data.toString(),
  39. count: 1
  40. });
  41. });
  42. }
  43. if (options.onoutput) {
  44. child.on('close', (code) => {
  45. options.onoutput({
  46. source: 'close',
  47. content: code,
  48. count: 1
  49. });
  50. });
  51. }
  52. child.on('error', (error) => {
  53. if (options.onerror) {
  54. options.onerror({
  55. type: 'event',
  56. error: error
  57. });
  58. }
  59. });
  60. } catch (ex) {
  61. if (options.onerror) {
  62. options.onerror({
  63. type: 'exception',
  64. error: ex
  65. });
  66. }
  67. }
  68. };
  69. module.exports = {
  70. execCommandAsync: execCommandAsync
  71. }