spawnExec.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const child_process = require("child_process");
  2. const spawnExec = (cmds,opts={}) => {
  3. let cmd = cmds[0];
  4. let proc = child_process.spawn(cmd, cmds.slice(1), opts);
  5. console.log(cmds.join(' '))
  6. return new Promise(function (resolve, reject) {
  7. let stdout = [];
  8. let stderr = [];
  9. proc.stdout.on("data", function (buf) {
  10. stdout.push(buf);
  11. // 回调函数
  12. opts.stdout && opts.stdout(buf);
  13. });
  14. proc.stderr.on("data", function (buf) {
  15. stderr.push(buf);
  16. // 回调函数
  17. opts.stderr && opts.stderr(buf);
  18. });
  19. proc.on("exit", function (code) {
  20. let stdoutAll = Buffer.concat(stdout);
  21. let stderrAll = Buffer.concat(stderr);
  22. // 回调函数
  23. opts.exit && opts.exit(code);
  24. code ? reject({
  25. code,
  26. stdout: stdoutAll.toString(),
  27. stderr: stderrAll.toString()
  28. }) : resolve({
  29. stdout: stdoutAll.toString(),
  30. stderr: stderrAll.toString()
  31. });
  32. });
  33. });
  34. }
  35. module.exports = spawnExec