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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: