Skip to content
Myr

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

7 files+259 added−39 removed

added:lib/pipe.js+42 added
modified:lib/promise.js-2 removed
added:test/pipe.js+78 added
modified:index.d.ts+40 added-9 removed
1import {type Buffer} from 'node:buffer';2import {type ChildProcess} from 'node:child_process';3import {type Stream, type Readable as ReadableStream} from 'node:stream';3import {type Stream, type Readable as ReadableStream, type Writable as WritableStream} from 'node:stream';45export type StdioOption =6 | 'pipe'7 | 'overlapped'
276 unmodified lines
284 */285 readonly nodeOptions?: string[];286} & Options<EncodingType>;287288type StdoutStderrAll = string | Buffer | undefined;289288export type ExecaReturnBase<StdoutStderrType> = {290export type ExecaReturnBase<StdoutStderrType extends StdoutStderrAll> = {291 /**292 The file and arguments that were run, for logging purposes.293294 This is not escaped and should not be executed directly as a process, including using `execa()` or `execaCommand()`.
52 unmodified lines
347 */348 signalDescription?: string;349};350349export type ExecaSyncReturnValue<StdoutStderrType = string> = {351export type ExecaSyncReturnValue<StdoutStderrType extends StdoutStderrAll = string> = {352} & ExecaReturnBase<StdoutStderrType>;353354/**355Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.
4 unmodified lines
360- timing out361- being canceled362- there's not enough memory or there are already too many child processes363*/362export type ExecaReturnValue<StdoutStderrType = string> = {364export type ExecaReturnValue<StdoutStderrType extends StdoutStderrAll = string> = {365 /**366 The output of the process with `stdout` and `stderr` interleaved.367368 This is `undefined` if either:
9 unmodified lines
378 */379 isCanceled: boolean;380} & ExecaSyncReturnValue<StdoutStderrType>;381380export type ExecaSyncError<StdoutStderrType = string> = {382export 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.385386 The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.
12 unmodified lines
399 */400 originalMessage?: string;401} & Error & ExecaReturnBase<StdoutStderrType>;402401export type ExecaError<StdoutStderrType = string> = {403export type ExecaError<StdoutStderrType extends StdoutStderrAll = string> = {404 /**405 The output of the process with `stdout` and `stderr` interleaved.406407 This is `undefined` if either:
18 unmodified lines
426 */427 forceKillAfterTimeout?: number | false;428};429428export type ExecaChildPromise<StdoutStderrType> = {430export 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).433434 This is `undefined` if either:
14 unmodified lines
449 /**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;453454 /**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 string459460 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.461462 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>;466467 /**468 Like `pipeStdout()` but piping the child process's `stderr` instead.469470 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>;474475 /**476 Combines both `pipeStdout()` and `pipeStderr()`.477478 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};483453export type ExecaChildProcess<StdoutStderrType = string> = ChildProcess &484export type ExecaChildProcess<StdoutStderrType extends StdoutStderrAll = string> = ChildProcess &485ExecaChildPromise<StdoutStderrType> &486Promise<ExecaReturnValue<StdoutStderrType>>;487488/**
98 unmodified lines
587 | ExecaReturnValue<string | Buffer>588 | ExecaSyncReturnValue<string | Buffer>589 | Array<string | number | ExecaReturnValue<string | Buffer> | ExecaSyncReturnValue<string | Buffer>>;590560type Execa$<StdoutStderrType = string> = {591type 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'])`.594595 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 lines
modified:index.js+6 added-2 removed
7 unmodified lines
8import onetime from 'onetime';9import {makeError} from './lib/error.js';10import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';11import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12import {addPipeMethods} from './lib/pipe.js';13import {handleInput, getSpawnedResult, makeAllStream, validateInputSync} from './lib/stream.js';14import {mergePromise, getSpawnedPromise} from './lib/promise.js';15import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';16import {logCommand, verboseDefault} from './lib/verbose.js';
83 unmodified lines
100 timedOut: false,101 isCanceled: false,102 killed: false,103 }));103 return mergePromise(dummySpawned, errorPromise);104 mergePromise(dummySpawned, errorPromise);105 return dummySpawned;106 }107108 const spawnedPromise = getSpawnedPromise(spawned);109 const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
52 unmodified lines
162 handleInput(spawned, parsed.options.input);163164 spawned.all = makeAllStream(spawned, parsed.options);165166 addPipeMethods(spawned);164 return mergePromise(spawned, handlePromiseOnce);167 mergePromise(spawned, handlePromiseOnce);168 return spawned;169}170171export function execaSync(file, args, options) {172 const parsed = handleArguments(file, args, options);
123 unmodified lines
modified:index.test-d.ts+38 added-1 removed
2 unmodified lines
3// `process.stdin`, `process.stderr`, and `process.stdout`4// to get treated as `any` by `@typescript-eslint/no-unsafe-assignment`.5import * as process from 'node:process';6import {type Readable as ReadableStream} from 'node:stream';7import {expectType, expectError} from 'tsd';7import {createWriteStream} from 'node:fs';8import {expectType, expectError, expectAssignable} from 'tsd';9import {10 $,11 execa,12 execaSync,
11 unmodified lines
24 const execaPromise = execa('unicorns');25 execaPromise.cancel();26 expectType<ReadableStream | undefined>(execaPromise.all);2728 const execaBufferPromise = execa('unicorns', {encoding: null});29 const writeStream = createWriteStream('output.txt');3031 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));4041 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));5051 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));6061 const unicornsResult = await execaPromise;62 expectType<string>(unicornsResult.command);63 expectType<string>(unicornsResult.escapedCommand);64 expectType<number>(unicornsResult.exitCode);
31 unmodified lines
96 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 lines
modified:readme.md+55 added-25 removed
18 unmodified lines
19- 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.2627## Install
87 unmodified lines
115[16:50:03.308] echo rainbows116rainbows117```118118### Pipe the child process stdout to the parent119### Redirect output to a file120121```js122import {execa} from 'execa';123123execa('echo', ['unicorns']).stdout.pipe(process.stdout);124// Similar to `echo unicorns > stdout.txt` in Bash125await execa('echo', ['unicorns']).pipeStdout('stdout.txt')126127// Similar to `echo unicorns 2> stdout.txt` in Bash128await execa('echo', ['unicorns']).pipeStderr('stderr.txt')129130// Similar to `echo unicorns &> stdout.txt` in Bash131await execa('echo', ['unicorns'], {all:true}).pipeAll('all.txt')132```133134### Save and pipe output from a child process135136```js137import {execa} from 'execa';138139const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout);140// Prints `unicorns`141console.log(stdout);142// Also returns 'unicorns'143```144145### Pipe multiple processes146147```js148import {execa} from 'execa';149150// Similar to `echo unicorns | cat` in Bash151const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));152console.log(stdout);153//=> 'unicorns'154```155156### Handling Errors157158```js159import {execa} from 'execa';
130 unmodified lines
290This 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)293294#### pipeStdout(target)295296[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)300301If 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).302303The [`stdout` option](#stdout-1) must be kept as `pipe`, its default value.304305#### pipeStderr(target)306307Like [`pipeStdout()`](#pipestdouttarget) but piping the child process's `stderr` instead.308309The [`stderr` option](#stderr-1) must be kept as `pipe`, its default value.310311#### pipeAll(target)312313Combines both [`pipeStdout()`](#pipestdouttarget) and [`pipeStderr()`](#pipestderrtarget).314315Either 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`.316317### execaSync(file, arguments?, options?)318319Execute a file synchronously.320
437 unmodified lines
758759console.log(await pRetry(run, {retries: 5}));760```761709### Save and pipe output from a child process710711Let's say you want to show the output of a child process in real-time while also saving it to a variable.712713```js714import {execa} from 'execa';715716const subprocess = execa('echo', ['foo']);717subprocess.stdout.pipe(process.stdout);718719const {stdout} = await subprocess;720console.log('child output:', stdout);721```722723### Redirect output to a file724725```js726import {execa} from 'execa';727728const subprocess = execa('echo', ['foo'])729subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))730```731762### Redirect input from a file763764```js765import {execa} from 'execa';
38 unmodified lines