CKTIS / JavaScript
TransformStream: transform, flush, and controller.enqueue
Process input chunks with `transform()`, emit results with `controller.enqueue()`, and release buffered output with `flush()` on normal close.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
new TransformStream()
new TransformStream(transformer)
new TransformStream(transformer, writableStrategy)
new TransformStream(transformer, writableStrategy, readableStrategy)
// Optional transformer methods:
transform(chunk, controller)
flush(controller)
// Output from either method:
controller.enqueue(chunk)TransformStream pairs an input side (writable) with an output side (readable). Pass an optional transformer object to the constructor. The next two optional arguments set queuing strategies for the writable and readable sides, in that order. This is a Web Streams API, not part of ECMAScript 2024; check support in your target runtime.
transform(chunk, controller) runs for each input chunk when it is ready to be processed. Emit zero, one, or several output chunks by calling controller.enqueue(chunk) that many times on the supplied TransformStreamDefaultController. The callback's return value is not output. Without transform(), chunks pass through unchanged.
The optional flush(controller) runs on normal writable close, after all input chunks have been transformed successfully. It can emit buffered leftovers before the API closes the readable side; it is not a cleanup hook for cancellation or abort. The API waits for a promise returned by either callback. A throw or rejection errors the stream, so keep any asynchronous work within the promise you return.
enqueue() delivers a chunk to the readable side, returns undefined, and throws TypeError if that side no longer accepts chunks. It does not wait for a consumer. Backpressure can delay processing later writes, but it is not a hard cap on calls to enqueue() within one callback. Connect a consumer before waiting for writes to finish.
Examples
(async () => {
const input = new ReadableStream({
start(sourceController) {
for (const value of [1, 2, 3]) sourceController.enqueue(value);
sourceController.close();
},
});
let pending = [];
const pairs = new TransformStream({
transform(chunk, controller) {
pending.push(chunk);
if (pending.length === 2) {
controller.enqueue(pending);
pending = [];
}
},
flush(controller) {
if (pending.length > 0) controller.enqueue(pending);
},
});
const output = [];
await input.pipeThrough(pairs).pipeTo(new WritableStream({
write(chunk) {
output.push(chunk);
},
}));
console.log(JSON.stringify(output));
})().catch((error) => console.error(error));Result
[[1,2],[3]]
By default, `pipeThrough()` forwards normal source closure to the transform's writable side, while `pipeTo()` consumes output as it arrives. `transform()` emits the pair `[1,2]`, and `flush()` emits the leftover item as `[3]`.
Related lessons
- JavaScript · Lesson 4 · Advanced · Version: 4