Real-Time Text Streaming with JavaScript

Hardik Desai avatar
Hardik Desai

23 September 2024

1 min read
Real-Time Text Streaming with JavaScript

Description

Learn how to handle real-time streaming text responses in JavaScript. This tutorial covers the essentials of using fetch, EventSource, and WebSocket to stream data efficiently and update your web applications dynamically.

Summary

This project demonstrates how to handle real-time streaming text responses using JavaScript. It includes examples using  fetchEventSource, and WebSocket to stream data and dynamically update web applications.

Features

  1. Real-time data updates
  2. Examples using fetch, EventSource, and WebSocket
  3. Practical use cases and code snippets

Source Code

1
const aiResponse = await fetch(
2
`api_url_with_keys`,
3
{
4
method: "POST",
5
headers: {
6
"Content-Type": "application/json",
7
},
8
body: JSON.stringify({
9
message : "Hello world",
10
}),
11
}
12
);
13
14
const reader = aiResponse.body?.getReader();
15
const decoder = new TextDecoder("utf-8");
16
17
while (true) {
18
const { value, done } = await reader.read();
19
if (done) break;
20
21
const chunk = decoder.decode(value, { stream: true });
22
const dataString = chunk.trim().split("\n");
23
24
dataString.forEach((data) => {
25
if (data.startsWith("data: ")) {
26
const json = JSON.parse(data.slice(6));
27
const text = json.candidates[0].content.parts[0].text;
28
29
// Append the text to the UI
30
const codeDiv = document.getElementById("code");
31
codeDiv.innerHTML += `<p>${text}</p>`;
32
}
33
});
34
}

Join the newsletter

Subscribe for weekly updates. No spams ever!

Copyright © 2024 | Hardik Desai | All Rights Reserved