ChartGPT以流返回结果node怎么实现
ChartGPT 以流返回结果 node 怎么实现
1.ChartGPT 以流返回结果 node 怎么实现?
2.我们前端应该怎么处理接收返回结果?
3.怎样实现打字机式将结果回显在我们页面上?
❓:1.ChartGPT 以流返回结果 node 怎么实现?
💡:
const http = require("http");
http
.createServer((req, res) => {
const url = req.url;
if (url.endsWith("/stream")) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
// 模拟大文本数据,这里使用一个字符串数组来表示大文本数据
const bigTextData = [
"Chunk 1 of big text data.",
"Chunk 2 of big text data.",
"Chunk 3 of big text data.",
// ... 更多的数据块
"Final chunk of big text data.",
];
// 模拟每隔一段时间发送一个数据块
let currentIndex = 0;
const interval = setInterval(() => {
if (currentIndex < bigTextData.length) {
res.write("data: " + bigTextData[currentIndex] + "\n\n");
currentIndex++;
} else {
// 发送完毕后,关闭连接
res.end();
clearInterval(interval);
}
}, 1000);
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
})
.listen(3000);
console.log("Server running at http://localhost:3000/");
直接运行
npm i http && node index.js
访问 http://localhost:3000/stream
❓:2.我们前端应该怎么处理接收返回结果?
💡:
这个请求是自己封装的一个fetch函数
封装自带取消请求功能的 fetch 请求
debouncedFetch('/api/stream').then(async res => {
const reader = res.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log('Data stream complete');
break;
}
const data = new TextDecoder('utf-8').decode(value) as string;
setResult(pre => pre.concat(data));
// 在这里可以将数据呈现到页面上
}
});
❓:怎样实现打字机效果?
💡:自己百度吧
## 希望内容对你有帮助,如果有错误请联系我 q: 1911509826,感谢支持
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
2022-01-19 React笔记——第二篇Ref
2022-01-19 React笔记——第一篇this.setState()