Streaming Files with Bun
0 108
🌊 Introduction to Streaming Files with Bun
When dealing with large files like videos, logs, or datasets, loading everything into memory isn't always the best idea. Instead, you can stream them — sending chunks of data as needed. Thanks to Bun’s fast, modern runtime, Streaming Files with Bun becomes not only easy but also extremely performant. In this post, we'll walk through how to implement file streaming using Bun in practical and optimized ways.
⚡ Why Use File Streaming?
File streaming is essential when:
- You want to reduce memory usage for large files.
- You need to deliver files efficiently over HTTP (e.g., video streaming).
- You’re working with real-time logs or continuous data feeds.
📁 Basic File Streaming in Bun
Bun supports Node.js-compatible readable streams, making it easy to pipe a file to the response in a server.
import { createReadStream } from 'fs';
import { serve } from 'bun';
serve({
port: 3000,
fetch(req) {
const fileStream = createReadStream('./large-file.txt');
return new Response(fileStream, {
headers: {
'Content-Type': 'text/plain'
}
});
}
});
🧠 Tip: Use createReadStream
instead of reading the entire file with readFile
when dealing with large files.
🎥 Streaming Media Files (Video/Audio)
To stream media files efficiently, you’ll need to handle HTTP range requests. Here's a simplified way to do that in Bun:
import { createReadStream, statSync } from 'fs';
import { serve } from 'bun';
serve({
port: 4000,
fetch(req) {
const filePath = './sample.mp4';
const stat = statSync(filePath);
const range = req.headers.get('range');
if (!range) {
return new Response('Range header required', { status: 416 });
}
const [startStr, endStr] = range.replace(/bytes=/, "").split("-");
const start = parseInt(startStr);
const end = endStr ? parseInt(endStr) : stat.size - 1;
const stream = createReadStream(filePath, { start, end });
return new Response(stream, {
status: 206,
headers: {
'Content-Range': `bytes ${start}-${end}/${stat.size}`,
'Accept-Ranges': 'bytes',
'Content-Length': end - start + 1,
'Content-Type': 'video/mp4'
}
});
}
});
🎯 This approach allows your Bun server to serve video in chunks, which is how modern browsers consume media streams.
🧪 Stream JSON or Log Data
Streaming isn’t limited to media — it’s great for logs or large JSON arrays too. Here's how you can stream a growing log file:
import { createReadStream } from 'fs';
import { serve } from 'bun';
serve({
port: 5000,
fetch(req) {
const stream = createReadStream('./logs/output.log');
return new Response(stream, {
headers: {
'Content-Type': 'text/plain'
}
});
}
});
This is perfect for log dashboards, data processing pipelines, or audit trails.
🧵 Using Bun.file() for Streaming
Bun provides a utility called Bun.file()
that makes it easier to work with file blobs and streaming:
serve({
port: 6000,
fetch(req) {
const file = Bun.file('./document.pdf');
return new Response(file.stream(), {
headers: {
'Content-Type': 'application/pdf'
}
});
}
});
✅ It's cleaner and fully supports readable streams, while also enabling you to get size, type, and buffer when needed.
🔒 Bonus: Add Caching Headers
To improve performance further, especially for static assets, you can set cache headers:
return new Response(file.stream(), {
headers: {
'Content-Type': 'application/pdf',
'Cache-Control': 'public, max-age=86400'
}
});
This helps browsers cache the response and reduces repeated network load.
✅ Final Thoughts
Streaming Files with Bun empowers developers to build efficient, scalable, and memory-conscious servers. Whether you're serving logs, documents, or high-res video, Bun's modern stream support and fast I/O make it ideal for such use cases.
With tools like createReadStream
and Bun.file().stream()
, Bun makes it incredibly easy to stream files the right way — giving users smooth, responsive experiences. Happy streaming! 📡
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments