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"))Typorithm · medium
Step 1 of 8 · intro card
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.
A ReadableStream body sends chunks as they are ready.
controller.enqueue pushes a chunk; controller.close ends it.
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" },
});
},
});Connect each part of the code to the concept before you type.
Wrapping Bun.file in a Response streams the file efficiently and infers the Content-Type from its extension.
new Response(Bun.file("./report.pdf"))A ReadableStream lets you push chunks to the client as they are ready instead of buffering the whole body.
const stream = new ReadableStream({controller.enqueue sends one chunk; the "data: ..." framing is the server-sent events format.
controller.enqueue("data: tick\n\n");controller.close() signals there are no more chunks, ending the response body.
controller.close();text/event-stream tells the browser to treat the streamed body as server-sent events.
"Content-Type": "text/event-stream"Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.