transform.md
This file
Path
docs/transform.md
57 lines · 2.0 KiB · Markdown
Last changed by
Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
History of this fileTake it
Allow passing generators to the `std*` options (#693)ehmickybefore adoptione8f6bbd
lines 1–57why, one step back1# Transforms23## Summary45Transforms map or filter the input or output of a child process. They are defined by passing an [async generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*) to the [`stdin`](../readme.md#stdin), [`stdout`](../readme.md#stdout-1), [`stderr`](../readme.md#stderr-1) or [`stdio`](../readme.md#stdio-1) option.67```js8import {execa} from 'execa';910const transform = async function * (chunks) {11 for await (const chunk of chunks) {12 yield chunk.toUpperCase();13 }14};1516const {stdout} = await execa('echo', ['hello'], {stdout: transform});17console.log(stdout); // HELLO18```1920## Encoding2122The `chunks` argument passed to the transform is an [`AsyncIterable<string>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). If the [`encoding`](../readme.md#encoding) option is `buffer`, it is an `AsyncIterable<Uint8Array>` instead.2324The transform can `yield` either a `string` or an `Uint8Array`, regardless of the `chunks` argument's type.2526## Filtering2728`yield` can be called 0, 1 or multiple times. Not calling `yield` enables filtering a specific chunk.2930```js31import {execa} from 'execa';3233const transform = async function * (chunks) {34 for await (const chunk of chunks) {35 if (!chunk.includes('secret')) {36 yield chunk;37 }38 }39};4041const {stdout} = await execa('echo', ['This is a secret.'], {stdout: transform});42console.log(stdout); // ''43```4445## Combining4647The [`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`.4849```js50await execa('echo', ['hello'], {stdout: [transform, 'inherit']});51```5253This also allows using multiple transforms.5455```js56await execa('echo', ['hello'], {stdout: [transform, otherTransform]});57```