transform.md
This file
Path
docs/transform.md
279 lines · 8.8 KiB · Markdown
Last changed by
Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
History of this fileTake it
Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
lines 1–4why, one step back1# Transforms23## Summary4Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 5why, one step back5Transforms 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*) or a [transform options object](#transform-options) to the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) or [`stdio`](../readme.md#optionsstdio) 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 back67```js8import {execa} from 'execa';9Simplify transforms syntax (#748)ehmickybefore adoptionfd00294
lines 10–12why, one step back10const 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 back13};14Make subprocess async iterable (#923)ehmickybefore adoption2e8e8c9
line 15why, one step back15const {stdout} = await execa('./run.js', {stdout: transform});Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
lines 16–20why, one step back16console.log(stdout); // HELLO17```1819## Encoding20Prevent handling binary data like text data (#924)ehmickybefore adoptionaf3aefd
line 21why, one step back21The `line` argument passed to the transform is a string by default.\Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 22why, one step back22However, if the [`binary`](#transformoptionsbinary) transform option is `true` or if the [`encoding`](../readme.md#optionsencoding) subprocess option is binary, it is an `Uint8Array` instead.Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
line 23why, one step back23Fix Markdown typos in documentation (#907)ehmickybefore adoption8ee5985
line 24why, one step back24The 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 back2526## Filtering27Line-wise transforms (#699)ehmickybefore adoption6dd804f
line 28why, one step back28`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 back2930```js31import {execa} from 'execa';32Simplify transforms syntax (#748)ehmickybefore adoptionfd00294
lines 33–35why, one step back33const 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 back36 }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 back4243## Binary data4445The transform iterates over lines by default.\Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 46why, one step back46However, if the [`binary`](#transformoptionsbinary) transform option is `true` or if the [`encoding`](../readme.md#optionsencoding) subprocess option is binary, it iterates over arbitrary chunks of data instead.Line-wise transforms (#699)ehmickybefore adoption6dd804f
lines 47–52why, one step back4748```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 back53- 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 back55Strip newlines in transforms (#919)ehmickybefore adoption26e9150
lines 56–57why, one step back56## Newlines57Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 58why, one step back58Unless the [`binary`](#transformoptionsbinary) transform option is `true`, the transform iterates over lines.Strip newlines in transforms (#919)ehmickybefore adoption26e9150
lines 59–67why, one step back59By 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```67Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 68why, one step back68However, if the [`preserveNewlines`](#transformoptionspreservenewlines) transform option is `true`, newlines are kept.Strip newlines in transforms (#919)ehmickybefore adoption26e9150
lines 69–99why, one step back6970```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```99Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 100why, one step back100However, if the [`preserveNewlines`](#transformoptionspreservenewlines) transform option is `true`, multiple `yield`s produce a single line instead.Strip newlines in transforms (#919)ehmickybefore adoption26e9150
lines 101–115why, one step back101102```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```115Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 116–117why, one step back116## Object mode117Prevent handling binary data like text data (#924)ehmickybefore adoptionaf3aefd
line 118why, one step back118By default, `stdout` and `stderr`'s transforms must return a string or an `Uint8Array`.\Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 119why, one step back119However, if the [`objectMode`](#transformoptionsobjectmode) transform option is `true`, any type can be returned instead, except `null` or `undefined`. The subprocess' [`result.stdout`](../readme.md#resultstdout)/[`result.stderr`](../readme.md#resultstderr) will be an array of values.Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 120–121why, one step back120121```jsSimplify transforms syntax (#748)ehmickybefore adoptionfd00294
lines 122–124why, one step back122const transform = function * (line) {123 yield JSON.parse(line);124};Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 125–127why, one step back125126const {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 back128 console.log(stdout); // {...}Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 129–131why, one step back129}130```131Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 132why, one step back132[`stdin`](../readme.md#optionsstdin) can also use `objectMode: true`.Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
lines 133–134why, one step back133134```jsSimplify transforms syntax (#748)ehmickybefore adoptionfd00294
lines 135–137why, one step back135const transform = function * (line) {136 yield JSON.stringify(line);137};Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
line 138why, one step back138Simplify transforms syntax (#748)ehmickybefore adoptionfd00294
line 139why, one step back139const input = [{event: 'example'}, {event: 'otherExample'}];Allow any type with transforms (#709)ehmickybefore adoptioned8b2ce
line 140why, one step back140await execa('./jsonlines-input.js', {stdin: [input, {transform, objectMode: true}]});Simplify transforms syntax (#748)ehmickybefore adoptionfd00294
lines 141–144why, one step back141```142143## Sharing state144Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 145why, one step back145State can be shared between calls of the [`transform`](#transformoptionstransform) and [`final`](#transformoptionsfinal) functions.Simplify transforms syntax (#748)ehmickybefore adoptionfd00294
lines 146–157why, one step back146147```js148let count = 0149150// Prefix line number151const transform = function * (line) {152 yield `[${count++}] ${line}`;153};154```155156## Finalizing157Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
line 158why, one step back158To create additional lines after the last one, a [`final`](#transformoptionsfinal) generator function can be used.Simplify transforms syntax (#748)ehmickybefore adoptionfd00294
lines 159–173why, one step back159160```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 back174```175Add support for `std*: TransformStream` option (#938)ehmickybefore adoption45824d6
line 176why, one step back176## Duplex/Transform streamsAdd support for `std*: duplex` option (#937)ehmickybefore adoption6ca44fb
line 177why, one step back177Add support for `std*: TransformStream` option (#938)ehmickybefore adoption45824d6
line 178why, one step back178A [`Duplex`](https://nodejs.org/api/stream.html#class-streamduplex) stream, Node.js [`Transform`](https://nodejs.org/api/stream.html#class-streamtransform) stream or web [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) can be used instead of a generator function.Add support for `std*: duplex` option (#937)ehmickybefore adoption6ca44fb
line 179why, one step back179Add support for `std*: TransformStream` option (#938)ehmickybefore adoption45824d6
lines 180–183why, one step back180Like generator functions, web `TransformStream` can be passed either directly or as a `{transform}` plain object. But `Duplex` and `Transform` must always be passed as a `{transform}` plain object.181182The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](#encoding) nor [`preserveNewlines`](#newlines) options.183Add support for `std*: duplex` option (#937)ehmickybefore adoption6ca44fb
lines 184–191why, one step back184```js185import {createGzip} from 'node:zlib';186import {execa} from 'execa';187188const {stdout} = await execa('./run.js', {stdout: {transform: createGzip()}});189console.log(stdout); // `stdout` is compressed with gzip190```191Add support for `std*: TransformStream` option (#938)ehmickybefore adoption45824d6
lines 192–198why, one step back192```js193import {execa} from 'execa';194195const {stdout} = await execa('./run.js', {stdout: new CompressionStream('gzip')});196console.log(stdout); // `stdout` is compressed with gzip197```198Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
lines 199–200why, one step back199## Combining200Improve headers in `readme.md` (#967)ehmickybefore adoptiona5dcf42
line 201why, one step back201The [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) and [`stdio`](../readme.md#optionsstdio) 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`.Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
lines 202–210why, one step back202203```js204await execa('echo', ['hello'], {stdout: [transform, 'inherit']});205```206207This also allows using multiple transforms.208209```js210await execa('echo', ['hello'], {stdout: [transform, otherTransform]});Add support for `std*: TransformStream` option (#938)ehmickybefore adoption45824d6
lines 211–216why, one step back211```212213Or saving to files.214215```js216await execa('./run.js', {stdout: [new CompressionStream('gzip'), {file: './output.gz'}]});Make subprocess async iterable (#923)ehmickybefore adoption2e8e8c9
lines 217–220why, one step back217```218219## Async iteration220Improve headers in `readme.md` (#967)ehmickybefore adoptiona5dcf42
line 221why, one step back221In some cases, [iterating](../readme.md#subprocessiterablereadableoptions) over the subprocess can be an alternative to transforms.Make subprocess async iterable (#923)ehmickybefore adoption2e8e8c9
lines 222–229why, one step back222223```js224import {execa} from 'execa';225226for await (const line of execa('./run.js')) {227 const prefix = line.includes('error') ? 'ERROR' : 'INFO';228 console.log(`${prefix}: ${line}`);229}Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
line 230why, one step back230```Improve documentation of transform options (#969)ehmickybefore adoption1e9e47e
lines 231–279why, one step back231232## Transform options233234A transform or an [array of transforms](#combining) can be passed to the [`stdin`](../readme.md#optionsstdin), [`stdout`](../readme.md#optionsstdout), [`stderr`](../readme.md#optionsstderr) or [`stdio`](../readme.md#optionsstdio) option.235236A transform is either a [generator function](#transformoptionstransform) or a plain object with the following members.237238### transformOptions.transform239240Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`241242Map or [filter](#filtering) the input or output of the subprocess.243244More info [here](#summary) and [there](#sharing-state).245246### transformOptions.final247248Type: `GeneratorFunction<string | Uint8Array | unknown>` | `AsyncGeneratorFunction<string | Uint8Array | unknown>`249250Create additional lines after the last one.251252[More info.](#finalizing)253254### transformOptions.binary255256Type: `boolean`\257Default: `false`258259If `true`, iterate over arbitrary chunks of `Uint8Array`s instead of line `string`s.260261More info [here](#encoding) and [there](#binary-data).262263### transformOptions.preserveNewlines264265Type: `boolean`\266Default: `false`267268If `true`, keep newlines in each `line` argument. Also, this allows multiple `yield`s to produces a single line.269270[More info.](#newlines)271272### transformOptions.objectMode273274Type: `boolean`\275Default: `false`276277If `true`, allow [`transformOptions.transform`](#transformoptionstransform) and [`transformOptions.final`](#transformoptionsfinal) to return any type, not just `string` or `Uint8Array`.278279[More info.](#object-mode)