Horje
How to Stream Response in JavaScript?

Streaming responses in JavaScript refers to the process of handling data from a server in chunks as it arrives, rather than waiting for the entire response to be received before processing it. This can be particularly useful for handling large datasets, real-time data, or improving the perceived performance of an application by providing data to the user as soon as it’s available.

There are several approaches to stream response in JavaScript which are as follows:

Using ReadableStream API

The ReadableStream API provides a way to handle streams of data in a more efficient and flexible manner. It allows you to read the response as it comes in, process it chunk by chunk, and act on it accordingly.

Folder Structure

Screenshot-2024-06-14-145021

folder structure

Example: To demonstrate streaming responses using the Readable Stream API in JavaScript.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>ReadableStream API Example</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="content">
        <h1>ReadableStream API Example</h1>
        <pre id="output"></pre>
    </div>
    <script src="app.js"></script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
}

#content {
    background: white;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
}

#output {
    white-space: pre-wrap;
    word-wrap: break-word;
    background: #eee;
    padding: 10px;
    border-radius: 5px;
    max-height: 300px;
    overflow-y: auto;
}
JavaScript
document.addEventListener("DOMContentLoaded", () => {
    const outputElement = document.getElementById('output');

    fetch('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            const reader = response
                .body
                .getReader();
            const decoder = new TextDecoder();
            let receivedLength = 0;

            return new ReadableStream({
                start(controller) {
                    function push() {
                        reader
                            .read()
                            .then(({ done, value }) => {
                                if (done) {
                                    controller.close();
                                    return;
                                }
                                receivedLength += value
                                    .length;
                                const chunk = decoder
                                    .decode(value, { stream: true });
                                outputElement
                                    .textContent += chunk;
                                controller
                                    .enqueue(value);
                                push();
                            });
                    }
                    push();
                }
            });
        })
        .then(stream => new Response(stream))
        .then(response => response.text())
        .then(data => {
            console.log("Streaming complete");
        })
        .catch(error => {
            console.error('Streaming error:', error);
        });
});

Output:

Screenshot-2024-06-03-102120

ReadableStream API response

Using XMLHttpRequest (XHR) Streaming

XMLHttpRequest can be used to stream responses by listening to the progress event, which provides updates as data arrives. This method is less modern but still widely supported and useful for certain applications.

Folder structure

Screenshot-2024-06-14-144848

Folder structure

Example: To demonstrate streaming responses in JavaScript using the XMLHttpRequest(XHR) method.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>XHR Streaming Example</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="content">
        <h1>XHR Streaming Example</h1>
        <pre id="output"></pre>
    </div>
    <script src="app.js"></script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
}

#content {
    background: white;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
}

#output {
    white-space: pre-wrap;
    word-wrap: break-word;
    background: #eee;
    padding: 10px;
    border-radius: 5px;
    max-height: 300px;
    overflow-y: auto;
}
JavaScript
document.addEventListener("DOMContentLoaded", () => {
    const outputElement = document.getElementById('output');
    const xhr = new XMLHttpRequest();

    xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 3) {
            const response = xhr.responseText;
            outputElement.textContent = response;
        }
    };

    xhr.onload = function () {
        if (xhr.status === 200) {
            console.log("Streaming complete");
        } else {
            console.error("Error:", xhr.statusText);
        }
    };

    xhr.onerror = function () {
        console.error("Request failed");
    };

    xhr.send();
});

Output:

Screenshot-2024-06-03-101133

XMLHttpRequest (XHR) Streaming




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Implement Gantt Chart in ReactJS? How to Implement Gantt Chart in ReactJS?
How to Fix &quot;Cannot read property &#039;click&#039; of null&quot; in JavaScript? How to Fix &quot;Cannot read property &#039;click&#039; of null&quot; in JavaScript?
Check Symmetrical Binary Tree using JavaScript Check Symmetrical Binary Tree using JavaScript
JavaScript Program to Print all Nodes that do not have any Siblings JavaScript Program to Print all Nodes that do not have any Siblings
Print the nodes having exactly one child in a Binary tree using JavaScript Print the nodes having exactly one child in a Binary tree using JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17