Bun では、Response オブジェクトはボディとして非同期ジェネレーター関数を受け入れることができます。これにより、レスポンス全体が準備されるのを待つのではなく、データが利用可能になったときにクライアントにストリーミングできます。
ts
Bun.serve({
port: 3000,
fetch(req) {
return new Response(
// 非同期ジェネレーター関数
async function* () {
yield "Hello, ";
await Bun.sleep(100);
yield "world!";
// TypedArray または Buffer も yield できます
yield new Uint8Array(["\n".charCodeAt(0)]);
},
{ headers: { "Content-Type": "text/plain" } },
);
},
});任意の非同期イテラブルを Response に直接渡すことができます。
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" } },
);
},
});