Bun

指南HTTP

使用 Bun 的非同步迭代器串流 HTTP 伺服器

在 Bun 中,Response 物件可以接受非同步產生器函式作為其主體。這允許您在資料可用時將其串流到用戶端,而不是等待整個回應準備就緒。

Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response(
      // An async generator function
      async function* () {
        yield "Hello, ";
        await Bun.sleep(100);
        yield "world!";

        // you can also yield a TypedArray or Buffer
        yield new Uint8Array(["\n".charCodeAt(0)]);
      },
      { headers: { "Content-Type": "text/plain" } },
    );
  },
});

您可以將任何非同步可迭代直接傳遞給 Response

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" } },
    );
  },
});