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
The walk stopped after 200 commits: lines older than 9f65b86 point at it.
100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 1–37why, one step back1<picture>2 <source media="(prefers-color-scheme: dark)" srcset="../media/logo_dark.svg">3 <img alt="execa logo" src="../media/logo.svg" width="400">4</picture>5<br>67# 🔀 Piping multiple subprocesses89## Array syntax1011A 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).1213```js14import {execa} from 'execa';1516// Similar to `npm run build | head -n 2` in shells17const {stdout} = await execa('npm', ['run', 'build'])18 .pipe('head', ['-n', '2']);19```2021## Template string syntax2223```js24const {stdout} = await execa`npm run build`25 .pipe`head -n 2`;26```2728## Advanced syntax2930```js31const subprocess = execa`head -n 2`;32const {stdout} = await execa`npm run build`33 .pipe(subprocess);34```3536## Options37Improve documentation of Execa methods (#1115)ehmickybefore adoptionca2e813
line 38why, one step back38[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.100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 39–68why, one step back3940```js41const {stdout} = await execa('npm', ['run', 'build'], subprocessOptions)42 .pipe('head', ['-n', '2'], subprocessOrPipeOptions);43```4445```js46const {stdout} = await execa(subprocessOptions)`npm run build`47 .pipe(subprocessOrPipeOptions)`head -n 2`;48```4950```js51const subprocess = execa(subprocessOptions)`head -n 2`;52const {stdout} = await execa(subprocessOptions)`npm run build`53 .pipe(subprocess, pipeOptions);54```5556## Result5758When 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.5960```js61const destinationResult = await execa`npm run build`62 .pipe`head -n 2`;63console.log(destinationResult.stdout); // First 2 lines of `npm run build`6465const sourceResult = destinationResult.pipedFrom[0];66console.log(sourceResult.stdout); // Full output of `npm run build`67```68Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 69–78why, one step back69## Iterate, stream and IPC7071Just 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.7273```js74for await (const line of execa`npm run build`.pipe`sort`) {75 console.log(line);76}77```78100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 79–143why, one step back79## Errors8081When 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.8283```js84try {85 await execa`npm run build`86 .pipe`head -n 2`;87} catch (error) {88 if (error.pipedFrom.length === 0) {89 // `npm run build` failure90 console.error(error);91 } else {92 // `head -n 2` failure93 console.error(error);94 // `npm run build` output95 console.error(error.pipedFrom[0].stdout);96 }9798 throw error;99}100```101102## Series of subprocesses103104```js105await execa`npm run build`106 .pipe`sort`107 .pipe`head -n 2`;108```109110## 1 source, multiple destinations111112```js113const subprocess = execa`npm run build`;114const [sortedResult, truncatedResult] = await Promise.all([115 subprocess.pipe`sort`,116 subprocess.pipe`head -n 2`,117]);118```119120## Multiple sources, 1 destination121122```js123const destination = execa`./log-remotely.js`;124await Promise.all([125 execa`npm run build`.pipe(destination),126 execa`npm run test`.pipe(destination),127]);128```129130## Source file descriptor131132By default, the source's [`stdout`](api.md#subprocessstdout) is used, but this can be changed using the [`from`](api.md#pipeoptionsfrom) piping option.133134```js135await execa`npm run build`136 .pipe({from: 'stderr'})`head -n 2`;137```138139## Destination file descriptor140141By default, the destination's [`stdin`](api.md#subprocessstdin) is used, but this can be changed using the [`to`](api.md#pipeoptionsto) piping option.142143```jsFix `.pipe()` with the `stdio` option and orphaned destination subprocessesSindre Sorhusbefore adoption8d3f0a9
lines 144–148why, one step back144await execa('npm', ['run', 'build'])145 .pipe('./log-remotely.js', [], {146 to: 'fd3',147 stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}],148 });100% test coverage (#1018)ehmickybefore adoption9f65b86
line 149why, one step back149```Fix `.pipe()` with the `stdio` option and orphaned destination subprocessesSindre Sorhusbefore adoption8d3f0a9
lines 150–151why, one step back150151Piping 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.100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 152–182why, one step back152153## Unpipe154155Piping can be stopped using the [`unpipeSignal`](api.md#pipeoptionsunpipesignal) piping option.156157The [`subprocess.pipe()`](api.md#subprocesspipefile-arguments-options) method will be rejected with a cancelation error. However, each subprocess will keep running.158159```js160const abortController = new AbortController();161162process.on('SIGUSR1', () => {163 abortController.abort();164});165166// If the process receives SIGUSR1, `npm run build` stopped being logged remotely.167// However, it keeps running successfully.168try {169 await execa`npm run build`170 .pipe({unpipeSignal: abortController.signal})`./log-remotely.js`;171} catch (error) {172 if (!abortController.signal.aborted) {173 throw error;174 }175}176```177178<hr>179180[**Next**: ⏳️ Streams](streams.md)\181[**Previous**: 🧙 Transforms](transform.md)\182[**Top**: Table of contents](../readme.md#documentation)