UNPKG

1.11 kBJavaScriptView Raw
1// eslint-disable-next-line unicorn/prefer-top-level-await
2const nativePromisePrototype = (async () => {})().constructor.prototype;
3
4const descriptors = ['then', 'catch', 'finally'].map(property => [
5 property,
6 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),
7]);
8
9// The return value is a mixin of `childProcess` and `Promise`
10export const mergePromise = (spawned, promise) => {
11 for (const [property, descriptor] of descriptors) {
12 // Starting the main `promise` is deferred to avoid consuming streams
13 const value = typeof promise === 'function'
14 ? (...args) => Reflect.apply(descriptor.value, promise(), args)
15 : descriptor.value.bind(promise);
16
17 Reflect.defineProperty(spawned, property, {...descriptor, value});
18 }
19};
20
21// Use promises instead of `child_process` events
22export const getSpawnedPromise = spawned => new Promise((resolve, reject) => {
23 spawned.on('exit', (exitCode, signal) => {
24 resolve({exitCode, signal});
25 });
26
27 spawned.on('error', error => {
28 reject(error);
29 });
30
31 if (spawned.stdin) {
32 spawned.stdin.on('error', error => {
33 reject(error);
34 });
35 }
36});