index.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { ChildProcessWithoutNullStreams, exec as shell_exec } from 'child_process';
  2. import { spawn as shell_spawn } from 'child_process';
  3. const MAX_BUFFER = 10 * Math.pow(2, 20);
  4. export function exec(command: string, stdout: (...args) => void | NodeJS.WriteStream, stderr: (...args) => void | NodeJS.WriteStream) {
  5. return new Promise<string>((resolve, reject) => {
  6. let stdoutbuf = "";
  7. let stderrbuf = "";
  8. // EXEC CHILD PROCESS
  9. const p = shell_exec(command, { maxBuffer: MAX_BUFFER }, (err, out) => {
  10. if (err) return reject(err);
  11. if (stdoutbuf.length > 0 && typeof stdout === 'function') stdout(stdoutbuf);
  12. if (stderrbuf.length > 0 && typeof stderr === 'function') stderr(stderrbuf);
  13. resolve(out);
  14. });
  15. // PIPE STDOUT
  16. if (typeof stdout === 'function') {
  17. p.stdout.on("data", chunk => {
  18. stdoutbuf += chunk;
  19. let i = -1;
  20. while ((i = stdoutbuf.indexOf('\n')) >= 0) {
  21. const line = stdoutbuf.substring(0, i);
  22. stdoutbuf = stdoutbuf.substring(i + 1);
  23. if (typeof stdout === 'function') {
  24. stdout(line);
  25. }
  26. }
  27. });
  28. } else if (typeof stdout !== 'undefined') {
  29. p.stdout.pipe(stdout);
  30. }
  31. // PIPE STDERR
  32. if (typeof stderr === 'function') {
  33. p.stderr.on("data", chunk => {
  34. stderrbuf += chunk;
  35. let i = -1;
  36. while ((i = stderrbuf.indexOf('\n')) >= 0) {
  37. const line = stderrbuf.substring(0, i);
  38. stderrbuf = stderrbuf.substring(i + 1);
  39. if (typeof stderr === 'function') {
  40. stderr(line);
  41. }
  42. }
  43. });
  44. } else if (typeof stderr !== 'undefined') {
  45. p.stderr.pipe(stderr);
  46. }
  47. });
  48. }
  49. export function spawn(command, args, stdout, stderr) {
  50. return new Promise<void>((resolve, reject) => {
  51. try {
  52. const p = shell_spawn(command, args);
  53. p.stdout.pipe(stdout);
  54. p.stderr.pipe(stderr);
  55. p.on('close', (code, sig) => {
  56. if (!code) resolve();
  57. else reject();
  58. });
  59. p.on('error', reject);
  60. p.on('exit', (code, sig) => {
  61. if (!code) resolve();
  62. else reject();
  63. });
  64. } catch (err) {
  65. console.error(err);
  66. }
  67. });
  68. }