index.ts 2.8 KB

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