執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

使用非同步迭代器的流式 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" } },
    );
  },
});