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 集合网址

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光头程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值