/
pipe.js
40 lines (31 loc) · 1.12 KB
/
pipe.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
import {Writable} from 'node:stream';
import {createWriteStream} from 'node:fs';
import {ChildProcess} from 'node:child_process';
const isWritableStream = target => target instanceof Writable;
const isExecaChildProcess = target => target instanceof ChildProcess && isWritableStream(target.stdin) && typeof target.then === 'function';
const pipeToTarget = (spawned, streamName, target) => {
if (typeof target === 'string') {
spawned[streamName].pipe(createWriteStream(target));
return spawned;
}
if (isWritableStream(target)) {
spawned[streamName].pipe(target);
return spawned;
}
if (isExecaChildProcess(target)) {
spawned[streamName].pipe(target.stdin);
return target;
}
throw new TypeError('The second argument must be a string, a stream or an Execa child process.');
};
export const addPipeMethods = spawned => {
if (spawned.stdout !== null) {
spawned.pipeStdout = pipeToTarget.bind(null, spawned, 'stdout');
}
if (spawned.stderr !== null) {
spawned.pipeStderr = pipeToTarget.bind(null, spawned, 'stderr');
}
if (spawned.all !== undefined) {
spawned.pipeAll = pipeToTarget.bind(null, spawned, 'all');
}
};