How Javascript TransformStream transform strings

Recently, All three browsers’ engines (Chrome, Safari, Firefox) started supporting the TransformStream API.

TransformStream allows you to break down a resource that you want to receive, send, or transform into small chunks, and then process these chunks bit by bit. Recently, Firefox 102 started to support TransformStream, which means TransformStream is now finally usable across browsers. Transform streams allow you to pipe from a ReadableStream to a WritableStream, executing a transformation on the chunks, or consuming the transformed result directly.

Following the example below, we demonstrate how to convert text file content into Uppercase form.

See the Pen
Untitled
by MahmoudJbor (@mahmoudjbor)
on CodePen.

First, we’ve declared UpperCaseTransformStream class, which does return a new TransformStream instance that takes the responsibility of converting the string chunks to uppercase.

class UpperCaseTransformStream {
    constructor() {
        return new TransformStream({
            transform(chunk, controller) {
                controller.enqueue(chunk.toUpperCase());
            },
        });
    }
}

Then, adding a listener to the Convert button, to read the file content and pass it through the UpperCaseTransformStream

button.addEventListener('click', async () => {
    var file = document.getElementById('fileForUpload').files[0];
    if (file) {
        var fileReader = new FileReader();
        fileReader.readAsText(file, 'UTF-8');
        window.selectedFile = file;

        fileReader.onload = async function (evt) {
            const res = new Response(evt.target.result);

            const readableStream = res.body
                .pipeThrough(new TextDecoderStream())
                .pipeThrough(new UpperCaseTransformStream());

            const reader = readableStream.getReader();
            let results = '';
            while (true) {
                const { done, value } = await reader.read();
                if (done) {
                    break;
                }
                results += value;
            }
            document.querySelector('pre').innerHTML = results;
            window.contentToDownload = results;
        };
        fileReader.onerror = function (evt) {
            document.querySelector('pre').innerHTML = 'Error reading the file';
        };
    }
});

Once this process is done, you will see the content transformed to Uppercase printed on the screen.

Photo from unslpash

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: