Skip to main content

Streaming HTTP Server with Async Iterators

还没翻译译自英文(bun.com)本页 3 段都还没译

In Bun, a Response accepts an async generator function as its body, so you can stream data to the client as it becomes available rather than waiting for the entire response to be ready.

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

You can pass any async iterable directly to 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" } },
    );
  },
});
翻訳 © 2026 fanyi.dev · 原文 © 2026 the Bun project (LICENSE.md names no copyright holder) (MIT)