4

How Javascript TransformStream transform strings

 2 years ago
source link: https://www.js-howto.com/how-javascript-transformstream-transform-strings/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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());
            },
        });
    }
}

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.

image-11-1024x318.png?resize=780%2C242&ssl=1

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK