DEV Community

Cover image for How Javascript TransformStream transform strings
MahmoudJbor
MahmoudJbor

Posted on • Originally published at js-howto.com

How Javascript TransformStream transform strings

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

TransformStream allows 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 consume the transformed result directly.

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

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());
            },
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

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';
        };
    }
});

Enter fullscreen mode Exit fullscreen mode

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

Original article link.

Top comments (0)