-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[doc] Add guide for streaming with async iterators
- Loading branch information
1 parent
26428d5
commit b6aebb5
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
--- | ||
name: Streaming HTTP Server with Async Iterators | ||
--- | ||
|
||
In Bun, [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects can accept an async generator function as their body. This allows you to stream data to the client as it becomes available, rather than waiting for the entire response to be ready. | ||
|
||
```ts | ||
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`: | ||
|
||
```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" } }, | ||
); | ||
}, | ||
}); | ||
``` |