transform.md
This file
Path
docs/transform.md
71 lines · 2.5 KiB · Markdown
Last changed by
Line-wise transforms (#699)ehmickybefore adoption6dd804f
History of this fileTake it
transform.md
Transforms
Summary
Transforms map or filter the input or output of a child process. They are defined by passing an async generator function to the stdin, stdout, stderr or stdio option.
import {execa} from 'execa';
const transform = async function * (lines) {
for await (const line of lines) {
const prefix = line.includes('error') ? 'ERROR' : 'INFO'
yield `${prefix}: ${line}`
}
};
const {stdout} = await execa('echo', ['hello'], {stdout: transform});
console.log(stdout); // HELLO
Encoding
The lines argument passed to the transform is an AsyncIterable<string>. If the encoding option is buffer, it is an AsyncIterable<Uint8Array> instead.
The transform can yield either a string or an Uint8Array, regardless of the lines argument's type.
Filtering
yield can be called 0, 1 or multiple times. Not calling yield enables filtering a specific line.
import {execa} from 'execa';
const transform = async function * (lines) {
for await (const line of lines) {
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 a {transform, binary: true} plain object is passed, it iterates over arbitrary chunks of data instead.
await 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.
Combining
The stdin, stdout, stderr and stdio 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.
await execa('echo', ['hello'], {stdout: [transform, 'inherit']});
This also allows using multiple transforms.
await execa('echo', ['hello'], {stdout: [transform, otherTransform]});