How to Stream Response in JavaScript?
Last Updated :
19 Jun, 2024
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
folder structureExample: 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:
ReadableStream API responseUsing 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
Folder structureExample: 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:
XMLHttpRequest (XHR) Streaming
Similar Reads
How to Use Streaming Parsing in JavaScript? Streaming parsing in JavaScript, particularly for large JSON files, processes data efficiently without loading the entire file into memory. This method is useful for handling large datasets and avoids memory issues by reading and processing data in chunks. It's especially beneficial for large files
2 min read
How to Convert JSON to Blob in JavaScript ? This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A light
2 min read
How to do Piping/Streaming of JavaScript objects in Node.js ? Node.js is well-known for its non-blocking I/O and stream-based data processing capabilities. While streams are typically used for handling raw binary data or strings, Node.js also provides mechanisms to stream JavaScript objects. This can be particularly useful for handling large datasets, processi
5 min read
How To Return the Response From an Asynchronous Call in JavaScript? To return the response from an asynchronous call in JavaScript, it's important to understand how JavaScript handles asynchronous operations like fetching data, reading files, or executing time-based actions. JavaScript is a single-threaded nature means it can only handle one task at a time, but it u
3 min read
Read JSON File Using JavaScript JSON (JavaScript Object Notation) is a lightweight format used for storing and exchanging data. In JavaScript, there are multiple ways to read and parse JSON files. These methods can be used both in browser environments and in Node.js.1. Using the fetch() API The fetch() API retrieves JSON files asy
3 min read
How To Fetch And Parse RSS Feeds In JavaScript? RSS (Really Simple Syndication) feeds are widely used for sharing updates from websites in a standardized XML format. By fetching and parsing RSS feeds, you can access the latest content from blogs, news sites, and other platforms. In this article, weâll explore how to fetch and parse RSS feeds usin
4 min read