-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.js
38 lines (28 loc) · 1.14 KB
/
command.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const { spawn } = require('child_process');
const run = (cmd, args, options = {}) => {
return new Promise((resolve, reject) => {
const discard = () => void 0;
const info = { out : [], err : [] }
const stdOutWrite = data => process.stdout.write(data);
const stdErrWrite = data => process.stderr.write(data);
const log = (key, func) => {
return (data) => {
info[key].push(data.toString());
func(data.toString());
}
}
let command = spawn(cmd, args);
options.out = options.mute ? discard : (typeof options.out == 'function' ? options.out : stdOutWrite);
options.err = options.mute ? discard : (typeof options.err == 'function' ? options.err : stdErrWrite);
command.stdout.on('data', log('out', options.out));
command.stderr.on('data', log('err', options.err));
command.stderr.on('close', code => {
if (code) {
reject({ code, err: info.err.join('') });
} else {
resolve(info.out.join(''));
}
});
});
}
module.exports = { run }