function parseRange(header, size) {
if (!header || !header.startsWith('bytes=')) return null;
const [rawStart, rawEnd] = header.replace('bytes=', '').split('-');
let start;
let end;
if (rawStart === '') {
// suffix range: last N bytes, e.g. bytes=-500
const suffix = parseInt(rawEnd, 10);
if (Number.isNaN(suffix)) return null;
start = Math.max(size - suffix, 0);
end = size - 1;
} else {
start = parseInt(rawStart, 10);
end = rawEnd === '' ? size - 1 : parseInt(rawEnd, 10);
}
if (Number.isNaN(start) || Number.isNaN(end)) return null;
if (start > end || start < 0 || end >= size) return null;
return { start, end, contentLength: end - start + 1 };
}
module.exports = { parseRange };
const fs = require('fs');
const { promisify } = require('util');
const { parseRange } = require('./parseRange');
const stat = promisify(fs.stat);
async function streamVideo(req, res, filePath) {
let fileStat;
try {
fileStat = await stat(filePath);
} catch (err) {
res.statusCode = 404;
return res.end('Not found');
}
const size = fileStat.size;
const rangeHeader = req.headers.range;
if (!rangeHeader) {
res.writeHead(200, {
'Content-Length': size,
'Content-Type': 'video/mp4',
'Accept-Ranges': 'bytes'
});
return fs.createReadStream(filePath).pipe(res);
}
const range = parseRange(rangeHeader, size);
if (!range) {
res.writeHead(416, { 'Content-Range': `bytes */${size}` });
return res.end();
}
const { start, end, contentLength } = range;
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${size}`,
'Accept-Ranges': 'bytes',
'Content-Length': contentLength,
'Content-Type': 'video/mp4'
});
const stream = fs.createReadStream(filePath, { start, end });
stream.on('error', () => {
res.destroy();
});
// client aborted the seek: free the fd instead of leaking it
res.on('close', () => {
stream.destroy();
});
stream.pipe(res);
}
module.exports = { streamVideo };
const express = require('express');
const path = require('path');
const { streamVideo } = require('./streamVideo');
const app = express();
const MEDIA_DIR = path.join(__dirname, 'media');
app.get('/videos/:name', (req, res) => {
const resolved = path.resolve(MEDIA_DIR, req.params.name);
// block path traversal outside the media directory
if (!resolved.startsWith(MEDIA_DIR + path.sep)) {
res.statusCode = 400;
return res.end('Invalid path');
}
streamVideo(req, res, resolved).catch((err) => {
console.error('stream failed', err);
if (!res.headersSent) res.statusCode = 500;
res.end();
});
});
app.listen(3000, () => {
console.log('video server listening on :3000');
});
Serving video for <video> playback is not a plain file download: browsers issue partial Range requests so users can seek instantly and the player only buffers what it needs. Responding with the whole file on every request wastes bandwidth and breaks seeking. This snippet shows how to honor Range headers with fs.createReadStream and the correct 206 Partial Content semantics.
The range parser tab (parseRange helper) isolates the fiddly part: reading a bytes=start-end header and normalizing it against the file size. It handles the common forms — bytes=0-, bytes=500-999, and the suffix form bytes=-500 meaning the last N bytes — and returns null for anything malformed or unsatisfiable so the caller can decide how to respond. Because HTTP byte ranges are inclusive on both ends, contentLength is end - start + 1, a classic off-by-one trap the helper centralizes.
The streamVideo controller tab wires this into a request handler. It first fs.stats the file to learn the total size, which is needed both to validate the range and to build headers. When no Range header is present it falls back to a normal 200 full-body response with Accept-Ranges: bytes, signaling to the client that ranged requests are supported. When a range is present but unsatisfiable, it replies 416 with a Content-Range: bytes */size header as the spec requires.
For a valid range it sends 206 Partial Content with Content-Range, Content-Length, and the video MIME type, then pipes fs.createReadStream(path, { start, end }) into the response. Streaming rather than buffering keeps memory flat regardless of file size, and pipe propagates backpressure so a slow client cannot force the server to read faster than it can send. The error and close handlers matter in production: if the client aborts a seek mid-stream, the stream is destroyed to release the file descriptor, avoiding leaks under heavy scrubbing.
The server wiring tab shows the route mounted on a tiny Express app, resolving and constraining the requested filename to a media directory to prevent path traversal. Together these files form the minimal, correct core of a self-hosted video endpoint that behaves the way browsers expect.
Related snips
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
export type Settled<R> =
| { status: 'fulfilled'; value: R }
| { status: 'rejected'; reason: unknown };
export interface ConcurrencyOptions {
limit: number;
Simple concurrency limiter for batch operations
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
package api
import (
"io"
"net/http"
"os"
Safe multipart uploads using temp files (bounded memory)
Share this code
Here's the card — post it anywhere.