UNPKG

3.05 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5const cross_spawn_1 = __importDefault(require("cross-spawn"));
6function spawnAsync(command, args, options = {}) {
7 const stubError = new Error();
8 const callerStack = stubError.stack ? stubError.stack.replace(/^.*/, ' ...') : null;
9 let child;
10 let promise = new Promise((resolve, reject) => {
11 let { ignoreStdio, ...nodeOptions } = options;
12 // @ts-ignore: cross-spawn declares "args" to be a regular array instead of a read-only one
13 child = (0, cross_spawn_1.default)(command, args, nodeOptions);
14 let stdout = '';
15 let stderr = '';
16 if (!ignoreStdio) {
17 if (child.stdout) {
18 child.stdout.on('data', (data) => {
19 stdout += data;
20 });
21 }
22 if (child.stderr) {
23 child.stderr.on('data', (data) => {
24 stderr += data;
25 });
26 }
27 }
28 let completionListener = (code, signal) => {
29 child.removeListener('error', errorListener);
30 let result = {
31 pid: child.pid,
32 output: [stdout, stderr],
33 stdout,
34 stderr,
35 status: code,
36 signal,
37 };
38 if (code !== 0) {
39 let argumentString = args && args.length > 0 ? ` ${args.join(' ')}` : '';
40 let error = signal
41 ? new Error(`${command}${argumentString} exited with signal: ${signal}`)
42 : new Error(`${command}${argumentString} exited with non-zero code: ${code}`);
43 if (error.stack && callerStack) {
44 error.stack += `\n${callerStack}`;
45 }
46 Object.assign(error, result);
47 reject(error);
48 }
49 else {
50 resolve(result);
51 }
52 };
53 let errorListener = (error) => {
54 if (ignoreStdio) {
55 child.removeListener('exit', completionListener);
56 }
57 else {
58 child.removeListener('close', completionListener);
59 }
60 Object.assign(error, {
61 pid: child.pid,
62 output: [stdout, stderr],
63 stdout,
64 stderr,
65 status: null,
66 signal: null,
67 });
68 reject(error);
69 };
70 if (ignoreStdio) {
71 child.once('exit', completionListener);
72 }
73 else {
74 child.once('close', completionListener);
75 }
76 child.once('error', errorListener);
77 });
78 // @ts-ignore: TypeScript isn't aware the Promise constructor argument runs synchronously and
79 // thinks `child` is not yet defined
80 promise.child = child;
81 return promise;
82}
83module.exports = spawnAsync;
84//# sourceMappingURL=spawnAsync.js.map
\No newline at end of file