Typorithm · medium

Streaming Responses

bun-streaming-responsebunstreamingreadablestreamfiles
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Streaming Responses

0%

Web & Sockets

Return a Response whose body is a ReadableStream to send data chunk by chunk, using controller.enqueue for each chunk and controller.close to finish — perfect for server-sent events with a text/event-stream header. For files, wrap Bun.file(path) in a Response to stream it efficiently with the right Content-Type.

Passing a ReadableStream as the Response body streams data to the client as it is produced. Inside start(controller) you call controller.enqueue(chunk) for each piece and controller.close() when done, so nothing buffers the whole payload in memory.

For server-sent events you stream chunks framed as "data: ...\n\n" and set the Content-Type header to text/event-stream so the browser parses them as SSE.

Bun.file(path) returns a lazy file handle; wrapping it in new Response(Bun.file("./report.pdf")) streams the file straight from disk and infers the Content-Type from the extension, with no manual read into memory.

01

A ReadableStream body sends chunks as they are ready.

02

controller.enqueue pushes a chunk; controller.close ends it.

03

new Response(Bun.file(path)) streams files with the right Content-Type.

Bun.serve({
  fetch(req) {
    if (req.url.endsWith("/file")) {
      return new Response(Bun.file("./report.pdf"));
    }
    const stream = new ReadableStream({
      start(controller) {
        controller.enqueue("data: tick\n\n");
        controller.close();
      },
    });
    return new Response(stream, {
      headers: { "Content-Type": "text/event-stream" },
    });
  },
});

Read the implementation

Connect each part of the code to the concept before you type.

1. Stream a file

Wrapping Bun.file in a Response streams the file efficiently and infers the Content-Type from its extension.

new Response(Bun.file("./report.pdf"))

2. Build a stream

A ReadableStream lets you push chunks to the client as they are ready instead of buffering the whole body.

const stream = new ReadableStream({

3. Push a chunk

controller.enqueue sends one chunk; the "data: ..." framing is the server-sent events format.

controller.enqueue("data: tick\n\n");

4. End the stream

controller.close() signals there are no more chunks, ending the response body.

controller.close();

5. SSE header

text/event-stream tells the browser to treat the streamed body as server-sent events.

"Content-Type": "text/event-stream"

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Streaming Responses: Lesson & Practice · Typorithm | ApplyDjinn