deno run --allow-net --unstable server.js
Created
September 17, 2021 17:17
-
-
Save matthewp/5d6cb7110dacce8727f5de2b8a7a800b to your computer and use it in GitHub Desktop.
streaming tests
This file contains hidden or 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
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