transform.md
This file
Path
docs/transform.md
157 lines · 5.4 KiB · Markdown
Last changed by
[docs] Transforms: Summary: Fix example command and output. (#1206)M.K.before adoptionc468672
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–20why, 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# 🧙 Transforms89## Summary1011Transforms 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](api.md#transform-options) to the [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout), [`stderr`](api.md#optionsstderr) or [`stdio`](api.md#optionsstdio) option. It can be [`async`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*).1213```js14import {execa} from 'execa';1516const transform = function * (line) {17 const prefix = line.includes('error') ? 'ERROR' : 'INFO';18 yield `${prefix}: ${line}`;19};20[docs] Transforms: Summary: Fix example command and output. (#1206)M.K.before adoptionc468672
lines 21–22why, one step back21const {stdout} = await execa({stdout: transform})`echo HELLO`;22console.log(stdout); // INFO: HELLOFix the type of the return value (#1007)ehmickybefore adoption0a13f2b
lines 23–157why, one step back23```2425## Difference with iteration2627Transforms operate one `line` at a time, just like [`subprocess.iterable()`](lines.md#progressive-splitting). However, unlike iteration, transforms:28- Modify the subprocess' [output](api.md#resultstdout) and [streams](api.md#subprocessstdout).29- Can apply to the subprocess' input.30- Are defined using a [generator function](#summary), [`Duplex`](#duplextransform-streams) stream, Node.js [`Transform`](#duplextransform-streams) stream or web [`TransformStream`](#duplextransform-streams).3132## Filtering3334`yield` can be called 0, 1 or multiple times. Not calling `yield` enables filtering a specific line.3536```js37const transform = function * (line) {38 if (!line.includes('secret')) {39 yield line;40 }41};4243const {stdout} = await execa({stdout: transform})`echo ${'This is a secret'}`;44console.log(stdout); // ''45```4647## Object mode4849By default, [`stdout`](api.md#optionsstdout) and [`stderr`](api.md#optionsstderr)'s transforms must return a string or an `Uint8Array`. However, if the [`objectMode`](api.md#transformoptionsobjectmode) transform option is `true`, any type can be returned instead, except `null` or `undefined`. The subprocess' [`result.stdout`](api.md#resultstdout)/[`result.stderr`](api.md#resultstderr) will be an array of values.5051```js52const transform = function * (line) {53 yield JSON.parse(line);54};5556const {stdout} = await execa({stdout: {transform, objectMode: true}})`node jsonlines-output.js`;57for (const data of stdout) {58 console.log(stdout); // {...object}59}60```6162[`stdin`](api.md#optionsstdin) can also use `objectMode: true`.6364```js65const transform = function * (line) {66 yield JSON.stringify(line);67};6869const input = [{event: 'example'}, {event: 'otherExample'}];70await execa({stdin: [input, {transform, objectMode: true}]})`node jsonlines-input.js`;71```7273## Sharing state7475State can be shared between calls of the [`transform`](api.md#transformoptionstransform) and [`final`](api.md#transformoptionsfinal) functions.7677```js78let count = 0;7980// Prefix line number81const transform = function * (line) {82 yield `[${count++}] ${line}`;83};84```8586## Finalizing8788To create additional lines after the last one, a [`final`](api.md#transformoptionsfinal) generator function can be used.8990```js91let count = 0;9293const transform = function * (line) {94 count += 1;95 yield line;96};9798const final = function * () {99 yield `Number of lines: ${count}`;100};101102const {stdout} = await execa({stdout: {transform, final}})`npm run build`;103console.log(stdout); // Ends with: 'Number of lines: 54'104```105106## Duplex/Transform streams107108A [`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.109110Like generator functions, web `TransformStream` can be passed either directly or as a [`{transform}` plain object](api.md#transform-options). But `Duplex` and `Transform` must always be passed as a `{transform}` plain object.111112The [`objectMode`](#object-mode) transform option can be used, but not the [`binary`](api.md#transformoptionsbinary) nor [`preserveNewlines`](api.md#transformoptionspreservenewlines) options.113114```js115import {createGzip} from 'node:zlib';116import {execa} from 'execa';117118const {stdout} = await execa({119 stdout: {transform: createGzip()},120 encoding: 'buffer',121})`npm run build`;122console.log(stdout); // `stdout` is compressed with gzip123```124125```js126const {stdout} = await execa({127 stdout: new CompressionStream('gzip'),128 encoding: 'buffer',129})`npm run build`;130console.log(stdout); // `stdout` is compressed with gzip131```132133## Combining134135The [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout), [`stderr`](api.md#optionsstderr) and [`stdio`](api.md#optionsstdio) options can accept [an array of values](output.md#multiple-targets). 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'`.136137```js138await execa({stdout: [transform, 'inherit']})`npm run build`;139```140141This also allows using multiple transforms.142143```js144await execa({stdout: [transform, otherTransform]})`npm run build`;145```146147Or saving to archives.148149```js150await execa({stdout: [new CompressionStream('gzip'), {file: './output.gz'}]})`npm run build`;151```152153<hr>154155[**Next**: 🔀 Piping multiple subprocesses](pipe.md)\156[**Previous**: 🤖 Binary data](binary.md)\157[**Top**: Table of contents](../readme.md#documentation)