Skip to content

Instantly share code, notes, and snippets.

@threepointone
Last active August 1, 2024 16:19
Show Gist options
  • Save threepointone/b473807287172c2bbe97726343f1f97b to your computer and use it in GitHub Desktop.
Save threepointone/b473807287172c2bbe97726343f1f97b to your computer and use it in GitHub Desktop.
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export default {
async fetch(): Promise<Response> {
// a simple streaming response
const encoder = new TextEncoder();
return new Response(
new ReadableStream({
async pull(controller) {
for (let i = 0; i < 5; i++) {
controller.enqueue(encoder.encode(`Hello world: ${i}\n`));
await sleep(1000);
}
controller.close();
},
}),
{
status: 200,
headers: {
"content-type": "text/plain", // this will buffer on chrome
// "content-type": "text/x-unknown", // this will not,
// some otehr explicit headers just in case
"content-encoding": "identity",
"transfer-encoding": "chunked",
},
}
);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment