Beginner LevelREST APIs & Web Services
How does HTTP 206 Partial Content and Range headers handle file streaming?
❓ Interview Prompt: Explain `206 Partial Content` status, `Range: bytes=0-1024` request header, `Content-Range` response header, and resumable video/file downloads.
Streaming large video files or downloading massive file archives uses HTTP Range Requests:
Execution Flow:
1
Client requests specific byte range: 'Range: bytes=0-1048575' (first 1 MB).
2
Server reads only those bytes from disk and returns '206 Partial Content' status.
3
Server returns headers: 'Content-Range: bytes 0-1048575/50000000' and 'Content-Length: 1048576'.
Code Implementation Example
typescript
import fs from 'fs';
import { Request, Response } from 'express';
export function streamVideo(req: Request, res: Response) {
const path = 'video.mp4';
const stat = fs.statSync(path);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = (end - start) + 1;
const file = fs.createReadStream(path, { start, end });
res.writeHead(206, {
'Content-Range': 'bytes \${start}-\${end}/\${fileSize}',
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
});
file.pipe(res);
}
}💡Streaming partial video byte chunks using 206 Partial Content and Range headers.
🎯 Interview Key Takeaway
Use HTTP Range headers and 206 Partial Content status to enable video scrubbing and resumable file downloads.
#206 Partial Content#Range Headers#File Streaming#Beginner
Back to all REST APIs & Web Services Questions→