UNPKG

2.33 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"));
6const bluebird_1 = __importDefault(require("bluebird"));
7const cache_stream_1 = __importDefault(require("./cache_stream"));
8class StatusError extends Error {
9}
10function promiseSpawn(command, args = [], options = {}) {
11 if (!command)
12 throw new TypeError('command is required!');
13 if (typeof args === 'string')
14 args = [args];
15 if (!Array.isArray(args)) {
16 options = args;
17 args = [];
18 }
19 return new bluebird_1.default((resolve, reject) => {
20 const task = (0, cross_spawn_1.default)(command, args, options);
21 const verbose = options.verbose;
22 const { encoding = 'utf8' } = options;
23 const stdoutCache = new cache_stream_1.default();
24 const stderrCache = new cache_stream_1.default();
25 if (task.stdout) {
26 const stdout = task.stdout.pipe(stdoutCache);
27 if (verbose)
28 stdout.pipe(process.stdout);
29 }
30 if (task.stderr) {
31 const stderr = task.stderr.pipe(stderrCache);
32 if (verbose)
33 stderr.pipe(process.stderr);
34 }
35 task.on('close', code => {
36 if (code) {
37 const e = new StatusError(getCache(stderrCache, encoding));
38 e.code = code;
39 return reject(e);
40 }
41 resolve(getCache(stdoutCache, encoding));
42 });
43 task.on('error', reject);
44 // Listen to exit events if neither stdout and stderr exist (inherit stdio)
45 if (!task.stdout && !task.stderr) {
46 task.on('exit', code => {
47 if (code) {
48 const e = new StatusError('Spawn failed');
49 e.code = code;
50 return reject(e);
51 }
52 resolve();
53 });
54 }
55 });
56}
57function getCache(stream, encoding) {
58 const buf = stream.getCache();
59 stream.destroy();
60 if (!encoding)
61 return buf;
62 return buf.toString(encoding);
63}
64module.exports = promiseSpawn;
65//# sourceMappingURL=spawn.js.map
\No newline at end of file