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

img

❓: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));
        // 在这里可以将数据呈现到页面上
      }
    });

❓:怎样实现打字机效果?
💡:自己百度吧

很全面 AI 集合网址

posted @ 2024-01-19 14:58  郭杰前端开发  阅读(29)  评论(0编辑  收藏  举报
## 希望内容对你有帮助,如果有错误请联系我 q: 1911509826,感谢支持