Node.jsadvanced
import { createReadStream, createWriteStream } from "node:fs";
import { finished } from "node:stream/promises";
export const copyWithCleanup = async (src: string, dest: string, signal?: AbortSignal) => {
const read = createReadStream(src);
Wait for a stream to finish and clean up resources without ad-hoc listeners.
Node.jsadvanced
import { createReadStream } from "node:fs";
import { Readable } from "node:stream";
export const compressedFileResponse = (path: string) => {
const nodeStream = createReadStream(path, { highWaterMark: 64 * 1024 });
Turn a Node Readable into a web-compatible stream with Readable.toWeb().
Node.jsintermediate
import { cp } from "node:fs/promises";
export const copyDirectory = (src: string, dest: string, options: { overwrite?: boolean } = {}) =>
cp(src, dest, {
recursive: true,
Copy directories in Node without shelling out to cp.
Node.jsintermediate
import { createServer, type ServerResponse } from "node:http";
const clients = new Set<ServerResponse>();
const server = createServer((req, res) => {
A live event stream over plain HTTP using res.write and text/event-stream — no WebSocket library, no socket.io, and free auto-reconnect in the browser.
Node.jsadvanced
export const createLRUCache = <K, V>(capacity: number) => {
const cache = new Map<K, V>();
const get = (key: K) => {
if (!cache.has(key)) return undefined;
A Map already tracks insertion order — re-inserting on access is enough to get real LRU eviction for free, no library needed.
Node.jsintermediate
import { watch } from "node:fs";
export const watchDebounced = (path: string, onChange: (eventType: string) => void, waitMs = 200) => {
let timer: NodeJS.Timeout | undefined;
fs.watch fires multiple times for a single logical change; debouncing it with a plain setTimeout gets you chokidar's core behavior for free.
Node.jsintermediate
export const retryWithBackoff = async <T>(fn: () => Promise<T>, maxAttempts = 5, baseDelayMs = 200): Promise<T> => {
for (let attempt = 1; ; attempt++) {
try {
return await fn();
} catch (err) {
Retry a failing async call with a delay that doubles each attempt plus random jitter, so retries don't pile onto a struggling service in lockstep.
Node.jsadvanced
export const createTokenBucket = (capacity: number, refillPerSecond: number) => {
let tokens = capacity;
let lastRefill = performance.now();
return (cost = 1): boolean => {
A token bucket that refills lazily based on elapsed time, so it needs no background timer to stay accurate.
Node.jsintermediate
import { Readable } from "node:stream";
async function* paginatedResults(pageCount: number) {
for (let page = 1; page <= pageCount; page++) {
await new Promise((resolve) => setTimeout(resolve, 10)); // simulate a network call
Readable.from() wraps any (async) generator or iterable in a real Readable stream, so it can be piped anywhere a stream is expected.
Node.jsadvanced
import { fork } from "node:child_process";
import { cpus } from "node:os";
import { once } from "node:events";
import { fileURLToPath } from "node:url";
Fork one child process per CPU core, split a CPU-bound range across them, and aggregate results over IPC — using one self-contained file.
Node.jsintermediate
import { performance } from "node:perf_hooks";
const benchmark = (fn: () => void, iterations = 100_000) => {
const start = process.hrtime.bigint();
for (let i = 0; i < iterations; i++) fn();
process.hrtime.bigint() gives nanosecond integer precision for micro-benchmarks; performance.now() is ms-resolution and good enough for most cases.
Node.jsintermediate
import { EventEmitter, once } from "node:events";
export const waitForReady = (emitter: EventEmitter) => once(emitter, "ready");
const bus = new EventEmitter();
events.once() turns a single EventEmitter event into an awaitable promise, replacing a one-shot .on() + manual .off() with one line.
Node.jsadvanced
import type { Writable } from "node:stream";
export const streamJsonArray = async (rows: AsyncIterable<unknown>, out: Writable) => {
out.write("[");
let first = true;
Write a large JSON array to a stream item by item as it's produced, instead of building the whole array in memory before calling JSON.stringify.
Node.jsintermediate
import { createServer } from "node:http";
const server = createServer((_req, res) => {
setTimeout(() => res.end("ok"), 50); // pretend this request takes a moment
});
Stop accepting new connections on SIGTERM, let in-flight requests finish, and force-exit if draining takes too long.
Node.jsadvanced
import { AsyncLocalStorage } from "node:async_hooks";
import { createServer } from "node:http";
import { randomUUID } from "node:crypto";
const requestContext = new AsyncLocalStorage<string>();
Thread a trace ID through every async call of a request, without passing it as an argument through every function in between.
Node.jsintermediate
import { test } from "node:test";
import assert from "node:assert/strict";
const add = (a: number, b: number) => a + b;
node:test plus node:assert/strict gives you a working test suite with zero dependencies and zero config files.
Node.jsintermediate
type Session = { id: string; startedAt: Date; roles: Set<string>; meta: Map<string, number> };
export const cloneSession = (session: Session): Session => structuredClone(session);
const original: Session = {
structuredClone() deep-copies Dates, Maps, Sets, and circular references correctly — JSON.parse(JSON.stringify()) silently mangles all four.
Node.jsadvanced
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
const fibonacci = (n: number): number => (n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2));
if (isMainThread) {
Offload a genuinely CPU-heavy computation to a worker_threads Worker so it stops blocking the event loop, using one self-contained file.
Node.jsadvanced
import { createReadStream, createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { Transform } from "node:stream";
const upperCaseChunks = new Transform({
Use stream/promises pipeline() to move data through a Transform without ever buffering more than the stream can hold.
Node.jsintermediate
export const fetchWithTimeout = async (url: string, timeoutMs: number) => {
const signal = AbortSignal.timeout(timeoutMs);
try {
const response = await fetch(url, { signal });
return await response.text();
Use AbortSignal.timeout() to cancel a fetch after N milliseconds and tell a timeout apart from every other kind of failure.