The TransformStream
interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept.
It may be passed to the ReadableStream.pipeThrough()
method in order to transform a stream of data from one format into another. For example, it might be used to decode (or encode) video frames, decompress data, or convert the stream from XML to JSON.
A transformation algorithm may be provided as an optional argument to the object constructor. If not supplied, data is not modified when piped through the stream.
TransformStream
is a transferable object.
In the following example, a transform stream passes through all chunks it receives as Uint8Array
values.
const transformContent = {
start() {},
async transform(chunk, controller) {
chunk = await chunk;
switch (typeof chunk) {
case "object":
if (chunk === null) {
controller.terminate();
} else if (ArrayBuffer.isView(chunk)) {
controller.enqueue(
new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
);
} else if (
Array.isArray(chunk) &&
chunk.every((value) => typeof value === "number")
) {
controller.enqueue(new Uint8Array(chunk));
} else if (
typeof chunk.valueOf === "function" &&
chunk.valueOf() !== chunk
) {
this.transform(chunk.valueOf(), controller);
} else if ("toJSON" in chunk) {
this.transform(JSON.stringify(chunk), controller);
}
break;
case "symbol":
controller.error("Cannot send a symbol as a chunk part");
break;
case "undefined":
controller.error("Cannot send undefined as a chunk part");
break;
default:
controller.enqueue(this.textencoder.encode(String(chunk)));
break;
}
},
flush() {
},
};
class AnyToU8Stream extends TransformStream {
constructor() {
super({ ...transformContent, textencoder: new TextEncoder() });
}
}
Note that this is deprecated by the native constructors. This is intended as a polyfill for unsupported platforms.
const tes = {
start() {
this.encoder = new TextEncoder();
},
transform(chunk, controller) {
controller.enqueue(this.encoder.encode(chunk));
},
};
let _jstes_wm = new WeakMap();
class JSTextEncoderStream extends TransformStream {
constructor() {
let t = { ...tes };
super(t);
_jstes_wm.set(this, t);
}
get encoding() {
return _jstes_wm.get(this).encoder.encoding;
}
}
Similarly, TextDecoderStream
can be written as such:
const tds = {
start() {
this.decoder = new TextDecoder(this.encoding, this.options);
},
transform(chunk, controller) {
controller.enqueue(this.decoder.decode(chunk, { stream: true }));
},
};
let _jstds_wm = new WeakMap();
class JSTextDecoderStream extends TransformStream {
constructor(encoding = "utf-8", { ...options } = {}) {
let t = { ...tds, encoding, options };
super(t);
_jstds_wm.set(this, t);
}
get encoding() {
return _jstds_wm.get(this).decoder.encoding;
}
get fatal() {
return _jstds_wm.get(this).decoder.fatal;
}
get ignoreBOM() {
return _jstds_wm.get(this).decoder.ignoreBOM;
}
}
This is a useful one, where multiple streams can be conjoined. Examples include building a PWA with progressive loading and progressive streaming.
let responses = [
];
let { readable, writable } = new TransformStream();
responses.reduce(
(a, res, i, arr) =>
a.then(() => res.pipeTo(writable, { preventClose: i + 1 !== arr.length })),
Promise.resolve(),
);
Note that this is not resilient to other influences.