Skip to content

Instantly share code, notes, and snippets.

@matthewp
Created September 17, 2021 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewp/5d6cb7110dacce8727f5de2b8a7a800b to your computer and use it in GitHub Desktop.
Save matthewp/5d6cb7110dacce8727f5de2b8a7a800b to your computer and use it in GitHub Desktop.
streaming tests
deno run --allow-net --unstable server.js
function createStream(iterator) {
const encoder = new TextEncoder();
return new ReadableStream({
async pull(controller) {
const { value, done } = await iterator.next();
if (done) {
controller.close();
} else {
const chunk = encoder.encode(value);
controller.enqueue(chunk);
}
},
});
}
const wait = () => new Promise(resolve => setTimeout(resolve, 2000));
async function * values() {
yield '<html><head><title>something</title></head><h1>1</h1>';
await wait();
yield '<h2>2</h2>';
await wait();
yield '<h3>3</h3>';
await wait();
yield '<h4>4</h4>';
await wait();
}
async function handle(conn) {
const httpConn = Deno.serveHttp(conn);
for await (const requestEvent of httpConn) {
const stream = createStream(values());
requestEvent.respondWith(new Response(stream, {
status: 200,
headers: {
'content-type': 'text/html',
'transfer-encoding': 'chunked'
}
}));
}
}
async function listen(server) {
for await (const conn of server) {
handle(conn);
}
}
export function startServer() {
const server = Deno.listen({ port: 8080 });
console.log(`Listening at http://localhost:${8080}`);
listen(server);
return server;
}
startServer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment