Deno logoDenoby example

Intermediate

clideploy

HTTP Server: Streaming

An example HTTP server that streams a response back to the client.

Import the http server from std/http.
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.
  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.
    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.
    cancel() {
      if (timer !== undefined) {
        clearInterval(timer);
      }
    },
  });
Return a response with the stream as the body.
  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.
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

Try this example in a Deno Deploy playground: