CKTIS / JavaScript
TransformStream — transforming a stream
TransformStream connects a writable side to a readable side. transform processes chunks, while flush can append final output before closure.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
new TransformStream({ transform(chunk, controller) { /* controller.enqueue(value) */ }, flush(controller) { /* optional final output */ } }, writableStrategy, readableStrategy)TransformStream is a Web API from the WHATWG Streams Standard, not an ECMAScript-defined feature. It exposes writable and readable; pipeThrough() connects them into a pipeline.
transform(chunk, controller) processes chunks sequentially. TransformStreamDefaultController.enqueue, called as controller.enqueue(value), emits output; returning a value alone does not. One chunk can produce zero or multiple outputs. Without transform, chunks pass through unchanged.
flush(controller) runs after all chunks are transformed during normal closure, not as universal error cleanup. It can emit a suffix. Both callbacks may return a Promise; exceptions or rejections error both sides.
Backpressure delays further writes: reading must progress concurrently. The example uses pipeTo(). Check API availability in the target browser; Node 24 does not establish browser support.
Examples
async function main() {
const source = new ReadableStream({
start(controller) {
controller.enqueue(2);
controller.enqueue(3);
controller.close();
}
});
let total = 0;
const double = new TransformStream({
transform(chunk, controller) {
total += chunk;
controller.enqueue(chunk * 2);
},
flush(controller) {
controller.enqueue(`sum=${total}`);
}
});
const output = [];
await source.pipeThrough(double).pipeTo(new WritableStream({
write(chunk) {
output.push(chunk);
}
}));
console.log(JSON.stringify(output));
}
main().catch(console.error);Result
[4,6,"sum=5"]
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.