文字流渲染
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>文字流渲染</title> </head> <body> <div id="">文字流渲染</div> <div id="text-container"></div> <script> const textContainer = document.getElementById("text-container"); const controller = new AbortController(); const signal = controller.signal; setTimeout(() => controller.abort(),2000); // 5秒超时 fetch("http://localhost:3000/stream", { signal }) .then((response) => { const reader = response.body.getReader(); function read() { return reader.read().then(({ done, value }) => { if (done) { return; } const text = new TextDecoder("utf-8").decode(value); textContainer.innerText += text; return read(); }); } return read(); }) .catch((err) => { if (err.name === "AbortError") { console.error("请求超时"); } else { console.error("请求失败", err); } }); </script> </body> </html>
Node起本地服务代码
const express = require('express'); const cors = require('cors'); const app = express(); const port = 3000; app.use(cors()); app.get('/stream', (req, res) => { res.setHeader('Content-Type', 'text/plain'); const text = "这是一个文字流示例这是一个文字流示例这是一个文字流示例这是一个文字流示例这是一个文字流示例这是一个文字流示例"; let index = 0; const interval = setInterval(() => { if (index < text.length) { res.write(text[index]); index++; } else { clearInterval(interval); res.end(); } }, 100); // 每隔100毫秒发送一个字符 }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
知识在于点滴积累