-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
55 lines (46 loc) · 1.29 KB
/
index.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// @flow
'use strict';
const crossSpawn = require('cross-spawn');
const { onExit } = require('signal-exit')
const EventEmitter = require('events');
const ChildProcessPromise = require('./promise');
const activeProcesses = new Set();
onExit(() => {
for (let child of activeProcesses) {
child.kill('SIGTERM');
}
});
function spawn(
cmd /*: string */,
args /*:: ?: Array<string> */,
opts /*:: ?: child_process$spawnOpts */
) /*: ChildProcessPromise */ {
return new ChildProcessPromise((resolve, reject, events) => {
let child = crossSpawn(cmd, args, opts);
let stdout = Buffer.from('');
let stderr = Buffer.from('');
activeProcesses.add(child);
if (child.stdout) {
child.stdout.on('data', data => {
stdout = Buffer.concat([stdout, data]);
events.emit('stdout', data);
});
}
if (child.stderr) {
child.stderr.on('data', data => {
stderr = Buffer.concat([stderr, data]);
events.emit('stderr', data);
});
}
child.on('error', err => {
activeProcesses.delete(child);
reject(err);
});
child.on('close', code => {
activeProcesses.delete(child);
resolve({ code, stdout, stderr });
});
});
}
module.exports = spawn;
module.exports.ChildProcessPromise = ChildProcessPromise;