| Event Loop |
Node.js is single-threaded but handles thousands of concurrent connections via non-blocking I/O. The event loop runs in phases: Timers (setTimeout/setInterval) → I/O callbacks → Poll (wait for I/O) → Check (setImmediate) → Close callbacks. I/O is delegated to libuv thread pool (OS) — the JS thread never waits |
process.nextTick() (runs before next loop iteration — use sparingly), setImmediate() (runs in Check phase), queueMicrotask() (Promises — runs after current operation, before next phase) |
❌ CPU-bound code (loops, crypto, image processing) blocks the event loop and stalls all concurrent requests. Never do heavy computation in a route handler — offload to worker_threads or a job queue |
Node.js Event Loop official, libuv docs |
| Modules — CJS vs ESM |
Two module systems exist. CommonJS (CJS): require()/module.exports — synchronous, dynamic. ES Modules (ESM): import/export — static, async, tree-shakeable. Node.js supports both but mixing them causes friction |
CJS: module.exports = { fn } / const { fn } = require('./module'). ESM: export const fn = ... / import { fn } from './module.js' (.js extension required). "type": "module" in package.json enables ESM globally |
❌ Cannot require() an ESM module (use dynamic import() instead). Cannot use __dirname/__filename in ESM — use import.meta.url + fileURLToPath. Most npm packages are still CJS — check compatibility before switching project to ESM |
Node.js ESM docs |
| Async Patterns |
Three generations: callbacks → Promises → async/await. async/await is syntactic sugar over Promises — understand Promises to debug async/await. Node.js core APIs mostly use callbacks — promisify them |
util.promisify(fs.readFile), Promise.all() (parallel — all must succeed), Promise.allSettled() (parallel — don't fail-fast), Promise.race() (first to resolve/reject wins), Promise.any() (first to resolve wins) |
❌ await inside a for loop = sequential (one at a time). Use Promise.all(array.map(async item => ...)) for parallel. Unhandled promise rejections crash the process in Node.js 15+ — always handle .catch() or use try/catch with await |
MDN Promises |
| Streams |
Process data piece-by-piece (chunks) without loading everything into memory. Four types: Readable (data source), Writable (data sink), Duplex (both), Transform (modify data in transit). Fundamental for file uploads, downloads, CSV processing, HTTP responses |
fs.createReadStream(), fs.createWriteStream(), .pipe(), stream.pipeline() (handles errors + cleanup — prefer over .pipe()), Transform stream for data transformation, readline for line-by-line file processing |
❌ .pipe() doesn't propagate errors — use stream.pipeline() instead. Backpressure: if consumer is slower than producer, buffer fills up → memory leak. Check writable.write() return value — false means pause reading |
Node.js Streams, stream.pipeline |
| Worker Threads |
Run CPU-intensive JavaScript in a separate thread — doesn't block the event loop. Workers share ArrayBuffer (zero-copy via SharedArrayBuffer/Atomics) or communicate via postMessage (copy) |
const worker = new Worker('./worker.js'), worker.postMessage(data), parentPort.on('message', ...), workerData for initial data, thread pool pattern for reusing workers |
❌ Worker threads are expensive to spawn — pool them (use workerpool or piscina library). Workers don't share memory by default (message passing = serialization overhead). Not for I/O-bound work — event loop handles that already |
Node.js Worker Threads, Piscina |
| Child Processes |
Run a separate process (shell command, Python script, another binary). Four methods: spawn (stream output), exec (buffer output), execFile (safer — no shell), fork (Node.js specific, IPC channel) |
spawn('ffmpeg', ['-i', input, output]) for long-running processes with streamed output. exec('ls -la', callback) for short commands. execFile to avoid shell injection. fork('./worker.js') for Node sub-processes with IPC |
❌ exec() with user input = shell injection vulnerability — always use spawn/execFile with args array. exec() buffers all output in memory — use spawn for large output. Child process crash doesn't automatically crash parent — handle exit/error events |
Node.js Child Processes |
File System (fs) |
Read/write files, directories, and file metadata. Two styles: callback-based (fs) and Promise-based (fs/promises). Always use fs/promises with async/await in modern code |
fs/promises: readFile, writeFile, appendFile, mkdir({ recursive: true }), readdir, stat, rename, unlink. Watch for changes: fs.watch(). Stream large files: createReadStream/createWriteStream |
❌ fs.readFileSync() / fs.writeFileSync() block the event loop — never use in production request handlers (only CLI scripts). fs.watch() fires events twice on some OS (debounce it). Always handle ENOENT (file not found) and EACCES (permission denied) errors |
Node.js fs/promises |
| Environment & Config |
Never hardcode secrets or environment-specific values. Use process.env for config. Validate all env vars at startup — crash early if required vars are missing |
.env file + dotenv (local dev). process.env.NODE_ENV (development/production/test). Validate with Zod at startup: const config = z.object({ DATABASE_URL: z.string().url(), PORT: z.coerce.number() }).parse(process.env) |
❌ Committing .env files to git = credential leak (use .gitignore). process.env values are always strings — parse numbers/booleans explicitly. No startup validation = mysterious runtime errors when env var is missing in production |
dotenv |
| Process Management |
Handle process lifecycle: graceful startup, graceful shutdown, signal handling, and crash recovery |
process.on('SIGTERM', gracefulShutdown), process.on('SIGINT', gracefulShutdown), process.on('unhandledRejection', (reason) => { logger.error(reason); process.exit(1) }), process.on('uncaughtException', ...) |
❌ No uncaughtException handler = process crashes silently. No graceful shutdown = in-flight requests dropped when container restarts. uncaughtException should log + exit — not swallow the error. PM2/Docker will restart the process after crash |
Node.js Process |