Certainly! Here's an example of using TransformStream in JavaScript:
// Create a custom transformer
const myTransformer = {
start(controller) {
controller.enqueue('Start of transformation.\n');
},
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
},
flush(controller) {
controller.enqueue('\nEnd of transformation.');
}
};
// Create a TransformStream using the custom transformer
const transformStream = new TransformStream(myTransformer);
// Get the writable and readable sides of the TransformStream
const writableStream = transformStream.writable;
const readableStream = transformStream.readable;
// Write some data to the writable side of the TransformStream
const writer = writableStream.getWriter();
writer.write('Hello, ');
writer.write('world!');
writer.close();
// Read the transformed data from the readable side of the TransformStream
const reader = readableStream.getReader();
reader.read().then(({ value, done }) => {
console.log(value); // Output: "START OF TRANSFORMATION.\nHELLO, WORLD!"
return reader.read();
}).then(({ value, done }) => {
console.log(value); // Output: "\nEND OF TRANSFORMATION."
return reader.read();
}).then(({ value, done }) => {
console.log(done); // Output: true
});
In this example:
-
We define a custom transformer object called myTransformer with three methods:
start: Called when the transformation starts. It enqueues the initial message.
transform: Called for each chunk of data. It transforms the chunk to uppercase and enqueues it.
flush: Called when the transformation ends. It enqueues the final message.
-
We create a new TransformStream instance, passing the myTransformer object as the transformer.
-
We get the writable and readable sides of the TransformStream using the writable and readable properties.
-
We write some data to the writable side of the TransformStream using a writer obtained from writableStream.getWriter(). We write two chunks of data: 'Hello, ' and 'world!', and then close the writer.
-
We read the transformed data from the readable side of the TransformStream using a reader obtained from readableStream.getReader(). We use the read() method to read the data chunks one by one.
-
We log the transformed data to the console. The first read() call outputs "START OF TRANSFORMATION.\nHELLO, WORLD!", the second call outputs "\nEND OF TRANSFORMATION.", and the third call outputs true, indicating that the stream is done.
This example demonstrates how to create a custom transformer, use it with a TransformStream, write data to the writable side, and read the transformed data from the readable side.
Note that TransformStream is a relatively new feature and may not be supported in all browsers. Make sure to check browser compatibility before using it in production.