运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

使用异步迭代器的流式 HTTP 服务器

在 Bun 中,Response 接受异步生成器函数作为其 body,因此你可以在数据可用时将其流式传输给客户端,而不必等待整个响应准备就绪。

stream-iterator.ts
Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response(
      // 一个异步生成器函数
      async function* () {
        yield "Hello, ";
        await Bun.sleep(100);
        yield "world!";

        // 你也可以 yield 一个 TypedArray 或 Buffer
        yield new Uint8Array(["\n".charCodeAt(0)]);
      },
      { headers: { "Content-Type": "text/plain" } },
    );
  },
});

你可以直接将任何异步可迭代对象传递给 Response:

stream-iterator.ts
Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response(
      {
        [Symbol.asyncIterator]: async function* () {
          yield "Hello, ";
          await Bun.sleep(100);
          yield "world!";
        },
      },
      { headers: { "Content-Type": "text/plain" } },
    );
  },
});