Add `pipeStdout()`-related methods (#531)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 69ce814 · Browse files · 7 files·+259 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
Diff stats
7 files+259 added−39 removed
- tests:+78 added−0 removed
- other:+181 added−39 removed
Provenance
- Commit
06287c8- Tree
d61d644- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
69ce814
7 files changed+259 added−39 removed
added:lib/pipe.js+42 added
123456789101112131415161718192021222324252627282930313233343536373839404142import {createWriteStream} from 'node:fs';import {ChildProcess} from 'node:child_process';import {isWritableStream} from 'is-stream';
const isExecaChildProcess = target => target instanceof ChildProcess && 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)) { throw new TypeError('The second argument must be a string, a stream or an Execa child process.'); }
if (!isWritableStream(target.stdin)) { throw new TypeError('The target child process\'s stdin must be available.'); }
spawned[streamName].pipe(target.stdin); return target;};
export const addPipeMethods = spawned => { if (spawned.stdout !== null) { spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout'); }
if (spawned.stderr !== null) { spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr'); }
if (spawned.all !== undefined) { spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all'); }};modified:lib/promise.js-2 removed
14 unmodified lines1516171819201920212214 unmodified lines14 unmodified lines : descriptor.value.bind(promise);
Reflect.defineProperty(spawned, property, {...descriptor, value}); }
return spawned;};
// Use promises instead of `child_process` eventsexport const getSpawnedPromise = spawned => new Promise((resolve, reject) => {14 unmodified linesadded:test/pipe.js+78 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import {PassThrough, Readable} from 'node:stream';import {spawn} from 'node:child_process';import {readFile} from 'node:fs/promises';import tempfile from 'tempfile';import test from 'ava';import getStream from 'get-stream';import {execa} from '../index.js';import {setFixtureDir} from './helpers/fixtures-dir.js';
setFixtureDir();
const pipeToProcess = async (t, fixtureName, funcName) => { const {stdout} = await execa(fixtureName, ['test'], {all: true})[funcName](execa('stdin.js')); t.is(stdout, 'test');};
test('pipeStdout() can pipe to Execa child processes', pipeToProcess, 'noop.js', 'pipeStdout');test('pipeStderr() can pipe to Execa child processes', pipeToProcess, 'noop-err.js', 'pipeStderr');test('pipeAll() can pipe stdout to Execa child processes', pipeToProcess, 'noop.js', 'pipeAll');test('pipeAll() can pipe stderr to Execa child processes', pipeToProcess, 'noop-err.js', 'pipeAll');
const pipeToStream = async (t, fixtureName, funcName, streamName) => { const stream = new PassThrough(); const result = await execa(fixtureName, ['test'], {all: true})[funcName](stream); t.is(result[streamName], 'test'); t.is(await getStream(stream), 'test\n');};
test('pipeStdout() can pipe to streams', pipeToStream, 'noop.js', 'pipeStdout', 'stdout');test('pipeStderr() can pipe to streams', pipeToStream, 'noop-err.js', 'pipeStderr', 'stderr');test('pipeAll() can pipe stdout to streams', pipeToStream, 'noop.js', 'pipeAll', 'stdout');test('pipeAll() can pipe stderr to streams', pipeToStream, 'noop-err.js', 'pipeAll', 'stderr');
const pipeToFile = async (t, fixtureName, funcName, streamName) => { const file = tempfile('.txt'); const result = await execa(fixtureName, ['test'], {all: true})[funcName](file); t.is(result[streamName], 'test'); t.is(await readFile(file, 'utf8'), 'test\n');};
test('pipeStdout() can pipe to files', pipeToFile, 'noop.js', 'pipeStdout', 'stdout');test('pipeStderr() can pipe to files', pipeToFile, 'noop-err.js', 'pipeStderr', 'stderr');test('pipeAll() can pipe stdout to files', pipeToFile, 'noop.js', 'pipeAll', 'stdout');test('pipeAll() can pipe stderr to files', pipeToFile, 'noop-err.js', 'pipeAll', 'stderr');
const invalidTarget = (t, funcName, getTarget) => { t.throws(() => execa('noop.js', {all: true})[funcName](getTarget()), { message: /a stream or an Execa child process/, });};
test('pipeStdout() can only pipe to writable streams', invalidTarget, 'pipeStdout', () => new Readable());test('pipeStderr() can only pipe to writable streams', invalidTarget, 'pipeStderr', () => new Readable());test('pipeAll() can only pipe to writable streams', invalidTarget, 'pipeAll', () => new Readable());test('pipeStdout() cannot pipe to non-processes', invalidTarget, 'pipeStdout', () => ({stdin: new PassThrough()}));test('pipeStderr() cannot pipe to non-processes', invalidTarget, 'pipeStderr', () => ({stdin: new PassThrough()}));test('pipeAll() cannot pipe to non-processes', invalidTarget, 'pipeStderr', () => ({stdin: new PassThrough()}));test('pipeStdout() cannot pipe to non-Execa processes', invalidTarget, 'pipeStdout', () => spawn('node', ['--version']));test('pipeStderr() cannot pipe to non-Execa processes', invalidTarget, 'pipeStderr', () => spawn('node', ['--version']));test('pipeAll() cannot pipe to non-Execa processes', invalidTarget, 'pipeStderr', () => spawn('node', ['--version']));
const invalidSource = (t, funcName) => { t.false(funcName in execa('noop.js', {stdout: 'ignore', stderr: 'ignore'}));};
test('Must set "stdout" option to "pipe" to use pipeStdout()', invalidSource, 'pipeStdout');test('Must set "stderr" option to "pipe" to use pipeStderr()', invalidSource, 'pipeStderr');test('Must set "stdout" or "stderr" option to "pipe" to use pipeAll()', invalidSource, 'pipeAll');
const invalidPipeToProcess = async (t, fixtureName, funcName) => { t.throws(() => execa(fixtureName, ['test'], {all: true})[funcName](execa('stdin.js', {stdin: 'ignore'})), { message: /stdin must be available/, });};
test('Must set target "stdin" option to "pipe" to use pipeStdout()', invalidPipeToProcess, 'noop.js', 'pipeStdout');test('Must set target "stdin" option to "pipe" to use pipeStderr()', invalidPipeToProcess, 'noop-err.js', 'pipeStderr');test('Must set target "stdin" option to "pipe" to use pipeAll()', invalidPipeToProcess, 'noop.js', 'pipeAll');modified:index.d.ts+40 added-9 removed
1 import {type Buffer} from 'node:buffer';2 import {type ChildProcess} from 'node:child_process';3-import {type Stream, type Readable as ReadableStream} from 'node:stream';3+import {type Stream, type Readable as ReadableStream, type Writable as WritableStream} from 'node:stream';4 5 export type StdioOption =6 | 'pipe'7 | 'overlapped'276 unmodified lines284 */285 readonly nodeOptions?: string[];286 } & Options<EncodingType>;287 288+type StdoutStderrAll = string | Buffer | undefined;289+288-export type ExecaReturnBase<StdoutStderrType> = {290+export type ExecaReturnBase<StdoutStderrType extends StdoutStderrAll> = {291 /**292 The file and arguments that were run, for logging purposes.293 294 This is not escaped and should not be executed directly as a process, including using `execa()` or `execaCommand()`.52 unmodified lines347 */348 signalDescription?: string;349 };350 349-export type ExecaSyncReturnValue<StdoutStderrType = string> = {351+export type ExecaSyncReturnValue<StdoutStderrType extends StdoutStderrAll = string> = {352 } & ExecaReturnBase<StdoutStderrType>;353 354 /**355 Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.4 unmodified lines360 - timing out361 - being canceled362 - there's not enough memory or there are already too many child processes363 */362-export type ExecaReturnValue<StdoutStderrType = string> = {364+export type ExecaReturnValue<StdoutStderrType extends StdoutStderrAll = string> = {365 /**366 The output of the process with `stdout` and `stderr` interleaved.367 368 This is `undefined` if either:9 unmodified lines378 */379 isCanceled: boolean;380 } & ExecaSyncReturnValue<StdoutStderrType>;381 380-export type ExecaSyncError<StdoutStderrType = string> = {382+export type ExecaSyncError<StdoutStderrType extends StdoutStderrAll = string> = {383 /**384 Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.385 386 The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.12 unmodified lines399 */400 originalMessage?: string;401 } & Error & ExecaReturnBase<StdoutStderrType>;402 401-export type ExecaError<StdoutStderrType = string> = {403+export type ExecaError<StdoutStderrType extends StdoutStderrAll = string> = {404 /**405 The output of the process with `stdout` and `stderr` interleaved.406 407 This is `undefined` if either:18 unmodified lines426 */427 forceKillAfterTimeout?: number | false;428 };429 428-export type ExecaChildPromise<StdoutStderrType> = {430+export type ExecaChildPromise<StdoutStderrType extends StdoutStderrAll> = {431 /**432 Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).433 434 This is `undefined` if either:14 unmodified lines449 /**450 Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This used to be preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`. But now this is deprecated and you should either use `.kill()` or the `signal` option when creating the child process.451 */452 cancel(): void;453+454+ /**455+ [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be:456+ - Another `execa()` return value457+ - A writable stream458+ - A file path string459+460+ If the `target` is another `execa()` return value, it is returned. Otherwise, the original `execa()` return value is returned. This allows chaining `pipeStdout()` then `await`ing the final result.461+462+ The `stdout` option] must be kept as `pipe`, its default value.463+ */464+ pipeStdout?<Target extends ExecaChildPromise<StdoutStderrAll>>(target: Target): Target;465+ pipeStdout?(target: WritableStream | string): ExecaChildProcess<StdoutStderrType>;466+467+ /**468+ Like `pipeStdout()` but piping the child process's `stderr` instead.469+470+ The `stderr` option must be kept as `pipe`, its default value.471+ */472+ pipeStderr?<Target extends ExecaChildPromise<StdoutStderrAll>>(target: Target): Target;473+ pipeStderr?(target: WritableStream | string): ExecaChildProcess<StdoutStderrType>;474+475+ /**476+ Combines both `pipeStdout()` and `pipeStderr()`.477+478+ Either the `stdout` option or the `stderr` option must be kept as `pipe`, their default value. Also, the `all` option must be set to `true`.479+ */480+ pipeAll?<Target extends ExecaChildPromise<StdoutStderrAll>>(target: Target): Target;481+ pipeAll?(target: WritableStream | string): ExecaChildProcess<StdoutStderrType>;482 };483 453-export type ExecaChildProcess<StdoutStderrType = string> = ChildProcess &484+export type ExecaChildProcess<StdoutStderrType extends StdoutStderrAll = string> = ChildProcess &485 ExecaChildPromise<StdoutStderrType> &486 Promise<ExecaReturnValue<StdoutStderrType>>;487 488 /**98 unmodified lines587 | ExecaReturnValue<string | Buffer>588 | ExecaSyncReturnValue<string | Buffer>589 | Array<string | number | ExecaReturnValue<string | Buffer> | ExecaSyncReturnValue<string | Buffer>>;590 560-type Execa$<StdoutStderrType = string> = {591+type Execa$<StdoutStderrType extends StdoutStderrAll = string> = {592 /**593 Same as `execa()` except both file and arguments are specified in a single tagged template string. For example, `` $`echo unicorns` `` is the same as `execa('echo', ['unicorns'])`.594 595 It's important to note that quotes, backslashes, and spaces are automatically escaped and have no special meaning unless the `shell` option is used. This escaping behavior also applies to interpolated expressions such as strings (`` $`echo ${'string'}` ``), arrays of strings (`` $`echo ${['array', 'of strings']}` ``), and so on.192 unmodified linesmodified:index.js+6 added-2 removed
7 unmodified lines8 import onetime from 'onetime';9 import {makeError} from './lib/error.js';10 import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';11 import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12+import {addPipeMethods} from './lib/pipe.js';13 import {handleInput, getSpawnedResult, makeAllStream, validateInputSync} from './lib/stream.js';14 import {mergePromise, getSpawnedPromise} from './lib/promise.js';15 import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';16 import {logCommand, verboseDefault} from './lib/verbose.js';83 unmodified lines100 timedOut: false,101 isCanceled: false,102 killed: false,103 }));103- return mergePromise(dummySpawned, errorPromise);104+ mergePromise(dummySpawned, errorPromise);105+ return dummySpawned;106 }107 108 const spawnedPromise = getSpawnedPromise(spawned);109 const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);52 unmodified lines162 handleInput(spawned, parsed.options.input);163 164 spawned.all = makeAllStream(spawned, parsed.options);165 166+ addPipeMethods(spawned);164- return mergePromise(spawned, handlePromiseOnce);167+ mergePromise(spawned, handlePromiseOnce);168+ return spawned;169 }170 171 export function execaSync(file, args, options) {172 const parsed = handleArguments(file, args, options);123 unmodified linesmodified:index.test-d.ts+38 added-1 removed
2 unmodified lines3 // `process.stdin`, `process.stderr`, and `process.stdout`4 // to get treated as `any` by `@typescript-eslint/no-unsafe-assignment`.5 import * as process from 'node:process';6 import {type Readable as ReadableStream} from 'node:stream';7-import {expectType, expectError} from 'tsd';7+import {createWriteStream} from 'node:fs';8+import {expectType, expectError, expectAssignable} from 'tsd';9 import {10 $,11 execa,12 execaSync,11 unmodified lines24 const execaPromise = execa('unicorns');25 execaPromise.cancel();26 expectType<ReadableStream | undefined>(execaPromise.all);27 28+ const execaBufferPromise = execa('unicorns', {encoding: null});29+ const writeStream = createWriteStream('output.txt');30+31+ expectAssignable<Function | undefined>(execaPromise.pipeStdout);32+ expectType<ExecaChildProcess>(execaPromise.pipeStdout!('file.txt'));33+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeStdout!('file.txt'));34+ expectType<ExecaChildProcess>(execaPromise.pipeStdout!(writeStream));35+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeStdout!(writeStream));36+ expectType<ExecaChildProcess>(execaPromise.pipeStdout!(execaPromise));37+ expectType<ExecaChildProcess<Buffer>>(execaPromise.pipeStdout!(execaBufferPromise));38+ expectType<ExecaChildProcess>(execaBufferPromise.pipeStdout!(execaPromise));39+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeStdout!(execaBufferPromise));40+41+ expectAssignable<Function | undefined>(execaPromise.pipeStderr);42+ expectType<ExecaChildProcess>(execaPromise.pipeStderr!('file.txt'));43+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeStderr!('file.txt'));44+ expectType<ExecaChildProcess>(execaPromise.pipeStderr!(writeStream));45+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeStderr!(writeStream));46+ expectType<ExecaChildProcess>(execaPromise.pipeStderr!(execaPromise));47+ expectType<ExecaChildProcess<Buffer>>(execaPromise.pipeStderr!(execaBufferPromise));48+ expectType<ExecaChildProcess>(execaBufferPromise.pipeStderr!(execaPromise));49+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeStderr!(execaBufferPromise));50+51+ expectAssignable<Function | undefined>(execaPromise.pipeAll);52+ expectType<ExecaChildProcess>(execaPromise.pipeAll!('file.txt'));53+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeAll!('file.txt'));54+ expectType<ExecaChildProcess>(execaPromise.pipeAll!(writeStream));55+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeAll!(writeStream));56+ expectType<ExecaChildProcess>(execaPromise.pipeAll!(execaPromise));57+ expectType<ExecaChildProcess<Buffer>>(execaPromise.pipeAll!(execaBufferPromise));58+ expectType<ExecaChildProcess>(execaBufferPromise.pipeAll!(execaPromise));59+ expectType<ExecaChildProcess<Buffer>>(execaBufferPromise.pipeAll!(execaBufferPromise));60+61 const unicornsResult = await execaPromise;62 expectType<string>(unicornsResult.command);63 expectType<string>(unicornsResult.escapedCommand);64 expectType<number>(unicornsResult.exitCode);31 unmodified lines96 expectType<number>(unicornsResult.exitCode);97 expectType<string>(unicornsResult.stdout);98 expectType<string>(unicornsResult.stderr);99 expectError(unicornsResult.all);100+ expectError(unicornsResult.pipeStdout);101+ expectError(unicornsResult.pipeStderr);102+ expectError(unicornsResult.pipeAll);103 expectType<boolean>(unicornsResult.failed);104 expectType<boolean>(unicornsResult.timedOut);105 expectError(unicornsResult.isCanceled);106 expectType<boolean>(unicornsResult.killed);209 unmodified linesmodified:readme.md+55 added-25 removed
18 unmodified lines19 - Higher max buffer. 100 MB instead of 200 KB.20 - [Executes locally installed binaries by name.](#preferlocal)21 - [Cleans up spawned processes when the parent process dies.](#cleanup)22 - [Get interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal. [*(Async only)*](#execasyncfile-arguments-options)23+- Convenience methods to [pipe processes' output](#redirect-output-to-a-file)24 - [Can specify file and arguments as a single string without a shell](#execacommandcommand-options)25 - More descriptive errors.26 27 ## Install87 unmodified lines115 [16:50:03.308] echo rainbows116 rainbows117 ```118 118-### Pipe the child process stdout to the parent119+### Redirect output to a file120 121 ```js122 import {execa} from 'execa';123 123-execa('echo', ['unicorns']).stdout.pipe(process.stdout);124+// Similar to `echo unicorns > stdout.txt` in Bash125+await execa('echo', ['unicorns']).pipeStdout('stdout.txt')126+127+// Similar to `echo unicorns 2> stdout.txt` in Bash128+await execa('echo', ['unicorns']).pipeStderr('stderr.txt')129+130+// Similar to `echo unicorns &> stdout.txt` in Bash131+await execa('echo', ['unicorns'], {all:true}).pipeAll('all.txt')132 ```133 134+### Save and pipe output from a child process135+136+```js137+import {execa} from 'execa';138+139+const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout);140+// Prints `unicorns`141+console.log(stdout);142+// Also returns 'unicorns'143+```144+145+### Pipe multiple processes146+147+```js148+import {execa} from 'execa';149+150+// Similar to `echo unicorns | cat` in Bash151+const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));152+console.log(stdout);153+//=> 'unicorns'154+```155+156 ### Handling Errors157 158 ```js159 import {execa} from 'execa';130 unmodified lines290 This is `undefined` if either:291 - the [`all` option](#all-2) is `false` (the default value)292 - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)293 294+#### pipeStdout(target)295+296+[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be:297+ - Another [`execa()` return value](#pipe-multiple-processes)298+ - A [writable stream](#save-and-pipe-output-from-a-child-process)299+ - A [file path string](#redirect-output-to-a-file)300+301+If the `target` is another [`execa()` return value](#execacommandcommand-options), it is returned. Otherwise, the original `execa()` return value is returned. This allows chaining `pipeStdout()` then `await`ing the [final result](#childprocessresult).302+303+The [`stdout` option](#stdout-1) must be kept as `pipe`, its default value.304+305+#### pipeStderr(target)306+307+Like [`pipeStdout()`](#pipestdouttarget) but piping the child process's `stderr` instead.308+309+The [`stderr` option](#stderr-1) must be kept as `pipe`, its default value.310+311+#### pipeAll(target)312+313+Combines both [`pipeStdout()`](#pipestdouttarget) and [`pipeStderr()`](#pipestderrtarget).314+315+Either the [`stdout` option](#stdout-1) or the [`stderr` option](#stderr-1) must be kept as `pipe`, their default value. Also, the [`all` option](#all-2) must be set to `true`.316+317 ### execaSync(file, arguments?, options?)318 319 Execute a file synchronously.320 437 unmodified lines758 759 console.log(await pRetry(run, {retries: 5}));760 ```761 709-### Save and pipe output from a child process710-711-Let's say you want to show the output of a child process in real-time while also saving it to a variable.712-713-```js714-import {execa} from 'execa';715-716-const subprocess = execa('echo', ['foo']);717-subprocess.stdout.pipe(process.stdout);718-719-const {stdout} = await subprocess;720-console.log('child output:', stdout);721-```722-723-### Redirect output to a file724-725-```js726-import {execa} from 'execa';727-728-const subprocess = execa('echo', ['foo'])729-subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))730-```731-762 ### Redirect input from a file763 764 ```js765 import {execa} from 'execa';38 unmodified lines