UNPKG

1.19 kBJavaScriptView Raw
1import {createWriteStream} from 'node:fs';
2import {ChildProcess} from 'node:child_process';
3import {isWritableStream} from 'is-stream';
4
5const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';
6
7const pipeToTarget = (spawned, streamName, target) => {
8 if (typeof target === 'string') {
9 spawned[streamName].pipe(createWriteStream(target));
10 return spawned;
11 }
12
13 if (isWritableStream(target)) {
14 spawned[streamName].pipe(target);
15 return spawned;
16 }
17
18 if (!isExecaChildProcess(target)) {
19 throw new TypeError('The second argument must be a string, a stream or an Execa child process.');
20 }
21
22 if (!isWritableStream(target.stdin)) {
23 throw new TypeError('The target child process\'s stdin must be available.');
24 }
25
26 spawned[streamName].pipe(target.stdin);
27 return target;
28};
29
30export const addPipeMethods = spawned => {
31 if (spawned.stdout !== null) {
32 spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout');
33 }
34
35 if (spawned.stderr !== null) {
36 spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr');
37 }
38
39 if (spawned.all !== undefined) {
40 spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all');
41 }
42};