pipe.md
This file
Path
docs/pipe.md
182 lines · 5.3 KiB · Markdown
Last changed by
Fix `.pipe()` with the `stdio` option and orphaned destination subprocessesSindre Sorhusbefore adoption8d3f0a9
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183<picture> <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg"> <img alt="execa logo" src="../media/logo.svg" width="400"></picture><br>
# 🔀 Piping multiple subprocesses
## Array syntax
A subprocess' [output](output.md) can be [piped](https://en.wikipedia.org/wiki/Pipeline_(Unix)) to another subprocess' [input](input.md). The syntax is the same as [`execa(file, arguments?, options?)`](execution.md#array-syntax).
```jsimport {execa} from 'execa';
// Similar to `npm run build | head -n 2` in shellsconst {stdout} = await execa('npm', ['run', 'build']) .pipe('head', ['-n', '2']);```
## Template string syntax
```jsconst {stdout} = await execa`npm run build` .pipe`head -n 2`;```
## Advanced syntax
```jsconst subprocess = execa`head -n 2`;const {stdout} = await execa`npm run build` .pipe(subprocess);```
## Options
[Options](api.md#options-1) can be passed to either the source or the destination subprocess. Some [pipe-specific options](api.md#pipeoptions) can also be set by the destination subprocess.
```jsconst {stdout} = await execa('npm', ['run', 'build'], subprocessOptions) .pipe('head', ['-n', '2'], subprocessOrPipeOptions);```
```jsconst {stdout} = await execa(subprocessOptions)`npm run build` .pipe(subprocessOrPipeOptions)`head -n 2`;```
```jsconst subprocess = execa(subprocessOptions)`head -n 2`;const {stdout} = await execa(subprocessOptions)`npm run build` .pipe(subprocess, pipeOptions);```
## Result
When both subprocesses succeed, the [`result`](api.md#result) of the destination subprocess is returned. The [`result`](api.md#result) of the source subprocess is available in a [`result.pipedFrom`](api.md#resultpipedfrom) array.
```jsconst destinationResult = await execa`npm run build` .pipe`head -n 2`;console.log(destinationResult.stdout); // First 2 lines of `npm run build`
const sourceResult = destinationResult.pipedFrom[0];console.log(sourceResult.stdout); // Full output of `npm run build````
## Iterate, stream and IPC
Just like a regular subprocess, the value returned by `subprocess.pipe()` can be [iterated](lines.md#progressive-splitting) over its output lines, [converted to a readable stream](streams.md#converting-a-subprocess-to-a-stream), or used to exchange [IPC messages](ipc.md) with the destination subprocess.
```jsfor await (const line of execa`npm run build`.pipe`sort`) { console.log(line);}```
## Errors
When either subprocess fails, `subprocess.pipe()` is rejected with that subprocess' error. If the destination subprocess fails, [`error.pipedFrom`](api.md#resultpipedfrom) includes the source subprocess' result, which is useful for debugging.
```jstry { await execa`npm run build` .pipe`head -n 2`;} catch (error) { if (error.pipedFrom.length === 0) { // `npm run build` failure console.error(error); } else { // `head -n 2` failure console.error(error); // `npm run build` output console.error(error.pipedFrom[0].stdout); }
throw error;}```
## Series of subprocesses
```jsawait execa`npm run build` .pipe`sort` .pipe`head -n 2`;```
## 1 source, multiple destinations
```jsconst subprocess = execa`npm run build`;const [sortedResult, truncatedResult] = await Promise.all([ subprocess.pipe`sort`, subprocess.pipe`head -n 2`,]);```
## Multiple sources, 1 destination
```jsconst destination = execa`./log-remotely.js`;await Promise.all([ execa`npm run build`.pipe(destination), execa`npm run test`.pipe(destination),]);```
## Source file descriptor
By default, the source's [`stdout`](api.md#subprocessstdout) is used, but this can be changed using the [`from`](api.md#pipeoptionsfrom) piping option.
```jsawait execa`npm run build` .pipe({from: 'stderr'})`head -n 2`;```
## Destination file descriptor
By default, the destination's [`stdin`](api.md#subprocessstdin) is used, but this can be changed using the [`to`](api.md#pipeoptionsto) piping option.
```jsawait execa('npm', ['run', 'build']) .pipe('./log-remotely.js', [], { to: 'fd3', stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}], });```
Piping sets the destination's [`stdin`](api.md#optionsstdin) option to `'pipe'`, unless the [`stdio`](api.md#optionsstdio) option is used, since those two options cannot be combined. In that case, the file descriptor targeted by the `to` option must already be an input [pipe](output.md#multiple-targets): `'pipe'` for `stdin`, or [`{value: 'pipe', input: true}`](input.md#additional-file-descriptors) for an additional file descriptor.
## Unpipe
Piping can be stopped using the [`unpipeSignal`](api.md#pipeoptionsunpipesignal) piping option.
The [`subprocess.pipe()`](api.md#subprocesspipefile-arguments-options) method will be rejected with a cancelation error. However, each subprocess will keep running.
```jsconst abortController = new AbortController();
process.on('SIGUSR1', () => { abortController.abort();});
// If the process receives SIGUSR1, `npm run build` stopped being logged remotely.// However, it keeps running successfully.try { await execa`npm run build` .pipe({unpipeSignal: abortController.signal})`./log-remotely.js`;} catch (error) { if (!abortController.signal.aborted) { throw error; }}```
<hr>
[**Next**: ⏳️ Streams](streams.md)\[**Previous**: 🧙 Transforms](transform.md)\[**Top**: Table of contents](../readme.md#documentation)