Skip to content
Myr

transform.md

This file

Path

docs/transform.md

213 lines · 6.4 KiB · Markdown

Last changed by

Add support for `std*: duplex` option (#937)ehmickybefore adoption6ca44fb

History of this file

Take it

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 1–4why, one step back
1# Transforms
23## Summary4

Rename `spawned` and `child process` to `subprocess` (#897)ehmickybefore adoption8fe2343

line 5why, one step back
5Transforms map or filter the input or output of a subprocess. They are defined by passing a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) to the [`stdin`](../readme.md#stdin), [`stdout`](../readme.md#stdout-1), [`stderr`](../readme.md#stderr-1) or [`stdio`](../readme.md#stdio-1) option. It can be [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*).

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 6–9why, one step back
6
7```js8import {execa} from 'execa';9

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

lines 10–12why, one step back
10const transform = function * (line) {
11 const prefix = line.includes('error') ? 'ERROR' : 'INFO';12 yield `${prefix}: ${line}`;

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 13–14why, one step back
13};
14

Make subprocess async iterable (#923)ehmickybefore adoption2e8e8c9

line 15why, one step back
15const {stdout} = await execa('./run.js', {stdout: transform});

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 16–20why, one step back
16console.log(stdout); // HELLO
17```1819## Encoding20

Prevent handling binary data like text data (#924)ehmickybefore adoptionaf3aefd

line 21why, one step back
21The `line` argument passed to the transform is a string by default.\

Improve handling of `encoding` option (#926)ehmickybefore adoptiond786fcf

line 22why, one step back
22However, if either a `{transform, binary: true}` plain object is passed, or if the [`encoding` option](../readme.md#encoding) is binary, it is an `Uint8Array` instead.

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

line 23why, one step back
23

Fix Markdown typos in documentation (#907)ehmickybefore adoption8ee5985

line 24why, one step back
24The transform can `yield` either a `string` or an `Uint8Array`, regardless of the `line` argument's type.

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 25–27why, one step back
25
26## Filtering27

Line-wise transforms (#699)ehmickybefore adoption6dd804f

line 28why, one step back
28`yield` can be called 0, 1 or multiple times. Not calling `yield` enables filtering a specific line.

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 29–32why, one step back
29
30```js31import {execa} from 'execa';32

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

lines 33–35why, one step back
33const transform = function * (line) {
34 if (!line.includes('secret')) {35 yield line;

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 36–41why, one step back
36 }
37};3839const {stdout} = await execa('echo', ['This is a secret.'], {stdout: transform});40console.log(stdout); // ''41```

Line-wise transforms (#699)ehmickybefore adoption6dd804f

lines 42–45why, one step back
42
43## Binary data4445The transform iterates over lines by default.\

Improve handling of `encoding` option (#926)ehmickybefore adoptiond786fcf

line 46why, one step back
46However, if either a `{transform, binary: true}` plain object is passed, or if the [`encoding` option](../readme.md#encoding) is binary, it iterates over arbitrary chunks of data instead.

Line-wise transforms (#699)ehmickybefore adoption6dd804f

lines 47–52why, one step back
47
48```js49await execa('./binary.js', {stdout: {transform, binary: true}});50```5152This is more efficient and recommended if the data is either:

Fix Markdown typos in documentation (#907)ehmickybefore adoption8ee5985

lines 53–54why, one step back
53- Binary: Which does not have lines.
54- Text: But the transform works even if a line or word is split across multiple chunks.

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

line 55why, one step back
55

Strip newlines in transforms (#919)ehmickybefore adoption26e9150

lines 56–115why, one step back
56## Newlines
5758Unless [`{transform, binary: true}`](#binary-data) is used, the transform iterates over lines.59By default, newlines are stripped from each `line` argument.6061```js62// `line`'s value never ends with '\n'.63const transform = function * (line) { /* ... */ };6465await execa('./run.js', {stdout: transform});66```6768However, if a `{transform, preserveNewlines: true}` plain object is passed, newlines are kept.6970```js71// `line`'s value ends with '\n'.72// The output's last `line` might or might not end with '\n', depending on the output.73const transform = function * (line) { /* ... */ };7475await execa('./run.js', {stdout: {transform, preserveNewlines: true}});76```7778Each `yield` produces at least one line. Calling `yield` multiple times or calling `yield *` produces multiples lines.7980```js81const transform = function * (line) {82 yield 'Important note:';83 yield 'Read the comments below.';8485 // Or:86 yield * [87 'Important note:',88 'Read the comments below.',89 ];9091 // Is the same as:92 yield 'Important note:\nRead the comments below.\n';9394 yield line95};9697await execa('./run.js', {stdout: transform});98```99100However, if a `{transform, preserveNewlines: true}` plain object is passed, multiple `yield`s produce a single line instead.101102```js103const transform = function * (line) {104 yield 'Important note: ';105 yield 'Read the comments below.\n';106107 // Is the same as:108 yield 'Important note: Read the comments below.\n';109110 yield line111};112113await execa('./run.js', {stdout: {transform, preserveNewlines: true}});114```115

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 116–117why, one step back
116## Object mode
117

Prevent handling binary data like text data (#924)ehmickybefore adoptionaf3aefd

lines 118–119why, one step back
118By default, `stdout` and `stderr`'s transforms must return a string or an `Uint8Array`.\
119However, if a `{transform, objectMode: true}` plain object is passed, any type can be returned instead, except `null` or `undefined`. The subprocess' [`stdout`](../readme.md#stdout)/[`stderr`](../readme.md#stderr) will be an array of values.

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 120–121why, one step back
120
121```js

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

lines 122–124why, one step back
122const transform = function * (line) {
123 yield JSON.parse(line);124};

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 125–127why, one step back
125
126const {stdout} = await execa('./jsonlines-output.js', {stdout: {transform, objectMode: true}});127for (const data of stdout) {

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

line 128why, one step back
128 console.log(stdout); // {...}

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 129–134why, one step back
129}
130```131132`stdin` can also use `objectMode: true`.133134```js

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

lines 135–137why, one step back
135const transform = function * (line) {
136 yield JSON.stringify(line);137};

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

line 138why, one step back
138

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

line 139why, one step back
139const input = [{event: 'example'}, {event: 'otherExample'}];

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

line 140why, one step back
140await execa('./jsonlines-input.js', {stdin: [input, {transform, objectMode: true}]});

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

lines 141–157why, one step back
141```
142143## Sharing state144145State can be shared between calls of the `transform` and [`final`](#finalizing) functions.146147```js148let count = 0149150// Prefix line number151const transform = function * (line) {152 yield `[${count++}] ${line}`;153};154```155156## Finalizing157

Allow using a `final` function without a `transform` (#916)ehmickybefore adoptionf8af153

line 158why, one step back
158To create additional lines after the last one, a `final` generator function can be used by passing a `{final}` or `{transform, final}` plain object.

Simplify transforms syntax (#748)ehmickybefore adoptionfd00294

lines 159–173why, one step back
159
160```js161let count = 0;162163const transform = function * (line) {164 count += 1;165 yield line;166};167168const final = function * () {169 yield `Number of lines: ${count}`;170};171172const {stdout} = await execa('./command.js', {stdout: {transform, final}});173console.log(stdout); // Ends with: 'Number of lines: 54'

Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce

lines 174–175why, one step back
174```
175

Add support for `std*: duplex` option (#937)ehmickybefore adoption6ca44fb

lines 176–187why, one step back
176## Node.js Duplex/Transform streams
177178A Node.js [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) or [`Transform`](https://nodejs.org/api/stream.html#class-streamtransform) stream can be used instead of a generator function. A `{transform}` plain object must be passed. The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](#encoding) nor [`preserveNewlines`](#newlines) options.179180```js181import {createGzip} from 'node:zlib';182import {execa} from 'execa';183184const {stdout} = await execa('./run.js', {stdout: {transform: createGzip()}});185console.log(stdout); // `stdout` is compressed with gzip186```187

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

lines 188–199why, one step back
188## Combining
189190The [`stdin`](../readme.md#stdin), [`stdout`](../readme.md#stdout-1), [`stderr`](../readme.md#stderr-1) and [`stdio`](../readme.md#stdio-1) options can accept an array of values. While this is not specific to transforms, this can be useful with them too. For example, the following transform impacts the value printed by `inherit`.191192```js193await execa('echo', ['hello'], {stdout: [transform, 'inherit']});194```195196This also allows using multiple transforms.197198```js199await execa('echo', ['hello'], {stdout: [transform, otherTransform]});

Make subprocess async iterable (#923)ehmickybefore adoption2e8e8c9

lines 200–212why, one step back
200```
201202## Async iteration203204In some cases, [iterating](../readme.md#iterablereadableoptions) over the subprocess can be an alternative to transforms.205206```js207import {execa} from 'execa';208209for await (const line of execa('./run.js')) {210 const prefix = line.includes('error') ? 'ERROR' : 'INFO';211 console.log(`${prefix}: ${line}`);212}

Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd

line 213why, one step back
213```