transform.md
This file
Path
docs/transform.md
230 lines · 7.0 KiB · Markdown
Last changed by
Add support for `std*: TransformStream` option (#938)ehmickybefore adoption45824d6
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231# Transforms
## Summary
Transforms 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*).
```jsimport {execa} from 'execa';
const transform = function * (line) { const prefix = line.includes('error') ? 'ERROR' : 'INFO'; yield `${prefix}: ${line}`;};
const {stdout} = await execa('./run.js', {stdout: transform});console.log(stdout); // HELLO```
## Encoding
The `line` argument passed to the transform is a string by default.\However, 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.
The transform can `yield` either a `string` or an `Uint8Array`, regardless of the `line` argument's type.
## Filtering
`yield` can be called 0, 1 or multiple times. Not calling `yield` enables filtering a specific line.
```jsimport {execa} from 'execa';
const transform = function * (line) { if (!line.includes('secret')) { yield line; }};
const {stdout} = await execa('echo', ['This is a secret.'], {stdout: transform});console.log(stdout); // ''```
## Binary data
The transform iterates over lines by default.\However, 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.
```jsawait execa('./binary.js', {stdout: {transform, binary: true}});```
This is more efficient and recommended if the data is either:- Binary: Which does not have lines.- Text: But the transform works even if a line or word is split across multiple chunks.
## Newlines
Unless [`{transform, binary: true}`](#binary-data) is used, the transform iterates over lines.By default, newlines are stripped from each `line` argument.
```js// `line`'s value never ends with '\n'.const transform = function * (line) { /* ... */ };
await execa('./run.js', {stdout: transform});```
However, if a `{transform, preserveNewlines: true}` plain object is passed, newlines are kept.
```js// `line`'s value ends with '\n'.// The output's last `line` might or might not end with '\n', depending on the output.const transform = function * (line) { /* ... */ };
await execa('./run.js', {stdout: {transform, preserveNewlines: true}});```
Each `yield` produces at least one line. Calling `yield` multiple times or calling `yield *` produces multiples lines.
```jsconst transform = function * (line) { yield 'Important note:'; yield 'Read the comments below.';
// Or: yield * [ 'Important note:', 'Read the comments below.', ];
// Is the same as: yield 'Important note:\nRead the comments below.\n';
yield line};
await execa('./run.js', {stdout: transform});```
However, if a `{transform, preserveNewlines: true}` plain object is passed, multiple `yield`s produce a single line instead.
```jsconst transform = function * (line) { yield 'Important note: '; yield 'Read the comments below.\n';
// Is the same as: yield 'Important note: Read the comments below.\n';
yield line};
await execa('./run.js', {stdout: {transform, preserveNewlines: true}});```
## Object mode
By default, `stdout` and `stderr`'s transforms must return a string or an `Uint8Array`.\However, 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.
```jsconst transform = function * (line) { yield JSON.parse(line);};
const {stdout} = await execa('./jsonlines-output.js', {stdout: {transform, objectMode: true}});for (const data of stdout) { console.log(stdout); // {...}}```
`stdin` can also use `objectMode: true`.
```jsconst transform = function * (line) { yield JSON.stringify(line);};
const input = [{event: 'example'}, {event: 'otherExample'}];await execa('./jsonlines-input.js', {stdin: [input, {transform, objectMode: true}]});```
## Sharing state
State can be shared between calls of the `transform` and [`final`](#finalizing) functions.
```jslet count = 0
// Prefix line numberconst transform = function * (line) { yield `[${count++}] ${line}`;};```
## Finalizing
To create additional lines after the last one, a `final` generator function can be used by passing a `{final}` or `{transform, final}` plain object.
```jslet count = 0;
const transform = function * (line) { count += 1; yield line;};
const final = function * () { yield `Number of lines: ${count}`;};
const {stdout} = await execa('./command.js', {stdout: {transform, final}});console.log(stdout); // Ends with: 'Number of lines: 54'```
## Duplex/Transform streams
A [`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.
Like 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.
The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](#encoding) nor [`preserveNewlines`](#newlines) options.
```jsimport {createGzip} from 'node:zlib';import {execa} from 'execa';
const {stdout} = await execa('./run.js', {stdout: {transform: createGzip()}});console.log(stdout); // `stdout` is compressed with gzip```
```jsimport {execa} from 'execa';
const {stdout} = await execa('./run.js', {stdout: new CompressionStream('gzip')});console.log(stdout); // `stdout` is compressed with gzip```
## Combining
The [`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`.
```jsawait execa('echo', ['hello'], {stdout: [transform, 'inherit']});```
This also allows using multiple transforms.
```jsawait execa('echo', ['hello'], {stdout: [transform, otherTransform]});```
Or saving to files.
```jsawait execa('./run.js', {stdout: [new CompressionStream('gzip'), {file: './output.gz'}]});```
## Async iteration
In some cases, [iterating](../readme.md#iterablereadableoptions) over the subprocess can be an alternative to transforms.
```jsimport {execa} from 'execa';
for await (const line of execa('./run.js')) { const prefix = line.includes('error') ? 'ERROR' : 'INFO'; console.log(`${prefix}: ${line}`);}```