Intermediate
clideploy
HTTP Server: Streaming
An example HTTP server that streams a response back to the client.
Import the http server from std/http.
!--frsh-copybutton:1-->
import { serve } from "https://deno.land/std@0.175.0/http/server.ts";
function handler(_req: Request): Response {
Set up a variable to store a timer ID, and the ReadableStream.
!--frsh-copybutton:2-->
let timer: number | undefined = undefined;
const body = new ReadableStream({
When the stream is first created, start an interval that will emit a chunk every second containing the current time.
!--frsh-copybutton:3-->
start(controller) {
timer = setInterval(() => {
const message = `It is ${new Date().toISOString()}\n`;
controller.enqueue(new TextEncoder().encode(message));
}, 1000);
},
If the stream is closed (the client disconnects), cancel the interval.
!--frsh-copybutton:4-->
cancel() {
if (timer !== undefined) {
clearInterval(timer);
}
},
});
Return a response with the stream as the body.
!--frsh-copybutton:5-->
return new Response(body, {
headers: {
"content-type": "text/plain",
"x-content-type-options": "nosniff",
},
});
}
To start the server on the default port, call `serve` with the handler.
!--frsh-copybutton:6-->
console.log("Listening on http://localhost:8000");
serve(handler);
Run this example locally using the Deno CLI:
deno run --allow-net https://byexample-wwv03xf36j0g.deno.dev/http-server-streaming.ts
Additional resources: