streams.md
This file
Path
docs/streams.md
139 lines · 7.7 KiB · Markdown
Last changed by
Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
History of this fileTake it
The walk stopped after 200 commits: lines older than 0a13f2b point at it.
Fix the type of the return value (#1007)ehmickybefore adoption0a13f2b
lines 1–106why, 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# ⏳️ Streams89## Node.js streams1011### Input1213```js14import {createReadStream} from 'node:fs';15import {once} from 'node:events';16import {execa} from 'execa';1718const readable = createReadStream('input.txt');19await once(readable, 'open');20await execa({stdin: readable})`npm run scaffold`;21```2223### Output2425```js26import {createWriteStream} from 'node:fs';27import {once} from 'node:events';28import {execa} from 'execa';2930const writable = createWriteStream('output.txt');31await once(writable, 'open');32await execa({stdout: writable})`npm run build`;33```3435### File descriptors3637When passing a Node.js stream to the [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout) or [`stderr`](api.md#optionsstderr) option, that stream must have an underlying file or socket, such as the streams created by the [`fs`](https://nodejs.org/api/fs.html#filehandlecreatereadstreamoptions), [`net`](https://nodejs.org/api/net.html#new-netsocketoptions) or [`http`](https://nodejs.org/api/http.html#class-httpincomingmessage) core modules. Otherwise the following error is thrown.3839```40TypeError [ERR_INVALID_ARG_VALUE]: The argument 'stdio' is invalid.41```4243This limitation can be worked around by either:44- Using the [`input`](api.md#optionsinput) option instead of the [`stdin`](api.md#optionsstdin) option.45- Passing a [web stream](#web-streams).46- Passing [`[nodeStream, 'pipe']`](output.md#multiple-targets) instead of `nodeStream`.4748## Web streams4950[Web streams](https://nodejs.org/api/webstreams.html) ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) or [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)) can be used instead of [Node.js streams](https://nodejs.org/api/stream.html).5152```js53const response = await fetch('https://example.com');54await execa({stdin: response.body})`npm run build`;55```5657## Iterables as input5859```js60const getReplInput = async function * () {61 for await (const replLine of getReplLines()) {62 yield replLine;63 }64};6566await execa({stdin: getReplInput()})`npm run scaffold`;67```6869## Manual streaming7071[`subprocess.stdin`](api.md#subprocessstdin) is a Node.js [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) stream and [`subprocess.stdout`](api.md#subprocessstdout)/[`subprocess.stderr`](api.md#subprocessstderr)/[`subprocess.all`](api.md#subprocessall) are Node.js [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) streams.7273They can be used to stream input/output manually. This is intended for advanced situations. In most cases, the following simpler solutions can be used instead:74- [`result.stdout`](output.md#stdout-and-stderr), [`result.stderr`](output.md#stdout-and-stderr) or [`result.stdio`](output.md#additional-file-descriptors).75- The [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout), [`stderr`](api.md#optionsstderr) or [`stdio`](api.md#optionsstdio) options.76- [`subprocess.iterable()`](lines.md#progressive-splitting).77- [`subprocess.pipe()`](pipe.md).7879## Converting a subprocess to a stream8081### Convert8283The [`subprocess.readable()`](api.md#subprocessreadablereadableoptions), [`subprocess.writable()`](api.md#subprocesswritablewritableoptions) and [`subprocess.duplex()`](api.md#subprocessduplexduplexoptions) methods convert the subprocess to a Node.js [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable), [`Writable`](https://nodejs.org/api/stream.html#class-streamwritable) and [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) stream.8485This is useful when using a library or API that expects Node.js streams as arguments. In every other situation, the simpler solutions described [above](#manual-streaming) can be used instead.8687```js88const readable = execa`npm run scaffold`.readable();8990const writable = execa`npm run scaffold`.writable();9192const duplex = execa`npm run scaffold`.duplex();93```9495### Different file descriptor9697By default, [`subprocess.readable()`](api.md#subprocessreadablereadableoptions), [`subprocess.writable()`](api.md#subprocesswritablewritableoptions) and [`subprocess.duplex()`](api.md#subprocessduplexduplexoptions) methods use [`stdin`](api.md#subprocessstdin) and [`stdout`](api.md#subprocessstdout). This can be changed using the [`from`](api.md#readableoptionsfrom) and [`to`](api.md#writableoptionsto) options.9899```js100const readable = execa`npm run scaffold`.readable({from: 'stderr'});101102const writable = execa`npm run scaffold`.writable({to: 'fd3'});103104const duplex = execa`npm run scaffold`.duplex({from: 'stderr', to: 'fd3'});105```106Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
lines 107–114why, one step back107Writing to an additional file descriptor like `'fd3'` requires marking it as [input](input.md#additional-file-descriptors), since it otherwise defaults to output.108109```js110const subprocess = execa({stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}]})`npm run scaffold`;111112const writable = subprocess.writable({to: 'fd3'});113```114Fix the type of the return value (#1007)ehmickybefore adoption0a13f2b
lines 115–120why, one step back115### Error handling116117When using [`subprocess.readable()`](api.md#subprocessreadablereadableoptions), [`subprocess.writable()`](api.md#subprocesswritablewritableoptions) or [`subprocess.duplex()`](api.md#subprocessduplexduplexoptions), the stream waits for the subprocess to end, and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](errors.md). This differs from [`subprocess.stdin`](api.md#subprocessstdin), [`subprocess.stdout`](api.md#subprocessstdout) and [`subprocess.stderr`](api.md#subprocessstderr)'s behavior.118119This means you do not need to `await` the subprocess' [promise](execution.md#result). On the other hand, you (or the library using the stream) do need to both consume the stream, and handle its `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.120Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
lines 121–134why, one step back121## Converting a subprocess to a web stream122123The [`subprocess.readableStream()`](api.md#subprocessreadablestreamreadableoptions), [`subprocess.writableStream()`](api.md#subprocesswritablestreamwritableoptions) and [`subprocess.transformStream()`](api.md#subprocesstransformstreamduplexoptions) methods are the [web streams](#web-streams) counterparts of [`subprocess.readable()`](api.md#subprocessreadablereadableoptions), [`subprocess.writable()`](api.md#subprocesswritablewritableoptions) and [`subprocess.duplex()`](api.md#subprocessduplexduplexoptions). They behave the same way, including [error handling](#error-handling) and the [`from`](api.md#readableoptionsfrom)/[`to`](api.md#writableoptionsto) options, but return a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream), a [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) and a [`{readable, writable}`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) pair instead of Node.js streams.124125This is useful when using a library or API that expects web streams as arguments. In every other situation, the [Node.js stream methods](#converting-a-subprocess-to-a-stream) can be used instead.126127```js128const readableStream = execa`npm run scaffold`.readableStream();129130const writableStream = execa`npm run scaffold`.writableStream();131132const {readable, writable} = execa`npm run scaffold`.transformStream();133```134Fix the type of the return value (#1007)ehmickybefore adoption0a13f2b
lines 135–139why, one step back135<hr>136137[**Next**: 📞 Inter-process communication](ipc.md)\138[**Previous**: 🔀 Piping multiple subprocesses](pipe.md)\139[**Top**: Table of contents](../readme.md#documentation)