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.
This project demonstrates how to handle real-time streaming text responses using JavaScript. It includes examples using fetch, EventSource, and WebSocket to stream data and dynamically update web applications.
Source Code
1const aiResponse = await fetch(2`api_url_with_keys`,3{4method: "POST",5headers: {6"Content-Type": "application/json",7},8body: JSON.stringify({9message : "Hello world",10}),11}12);1314const reader = aiResponse.body?.getReader();15const decoder = new TextDecoder("utf-8");1617while (true) {18const { value, done } = await reader.read();19if (done) break;2021const chunk = decoder.decode(value, { stream: true });22const dataString = chunk.trim().split("\n");2324dataString.forEach((data) => {25if (data.startsWith("data: ")) {26const json = JSON.parse(data.slice(6));27const text = json.candidates[0].content.parts[0].text;2829// Append the text to the UI30const codeDiv = document.getElementById("code");31codeDiv.innerHTML += `<p>${text}</p>`;32}33});34}
Join the newsletter
Subscribe for weekly updates. No spams ever!
Copyright © 2024 | Hardik Desai | All Rights Reserved