📡 You're offline — showing cached content
New version available!
Quick Access
Node.js Reference

Node.js Core

Event loop, modules, file system, and Express.js.

All Topics

Core Modules

require() vs import
CommonJS (require) = synchronous, runtime. ESM (import) = static, tree-shakeable. Use .mjs or package.json "type":"module" for ESM.
Example: import { readFile } from 'node:fs/promises'; // ESM with explicit node: prefix
fs.promises / fs.readFile
Always use fs.promises (async) or fs.readFileSync only at startup. Async I/O is non-blocking.
Example: const data = await fs.promises.readFile('./config.json', 'utf8'); JSON.parse(data);
path.join / path.resolve
join concatenates with OS separator. resolve from cwd to absolute path. Use __dirname or import.meta.url.
Example: const abs = path.resolve(import.meta.dirname, '../data/seed.json');
os.cpus() / os.freemem()
System info — number of CPUs for worker pool sizing, free/total memory for health checks.
Example: const workers = Math.max(1, os.cpus().length - 1);
process.env / process.argv
Environment variables / CLI arguments (index 0=node, 1=script, 2+ = user args).
Example: const port = parseInt(process.env.PORT ?? '3000', 10);
process.exit(code) / SIGTERM
Graceful shutdown — listen for SIGTERM/SIGINT, drain connections, then exit(0).
Example: process.on('SIGTERM', async () => { await server.close(); process.exit(0); });
child_process.spawn / exec
spawn = streaming output (large data). exec = buffered output, command string (shell injection risk).
Example: const { stdout } = await execFile('git', ['log', '--oneline', '-5']);
crypto module
Built-in cryptography — hashing, HMAC, AES encryption, random bytes, UUID generation.
Example: import { randomUUID, createHmac } from 'node:crypto'; randomUUID(); // v4 UUID

HTTP & Express.js

http.createServer
Raw HTTP server. Rarely used directly — use Express/Fastify/Hono. req/res are streams.
Example: http.createServer((req, res) => { res.writeHead(200); res.end('OK'); }).listen(3000);
express() app structure
Middleware chain — each middleware calls next() to pass control. Order matters.
Example: app.use(express.json()); app.use(cors()); app.use('/api', router); app.use(errorHandler);
Router / router.param()
Modular route groups. router.param auto-loads resource when param is present in route.
Example: router.param('id', async (req,res,next,id) => { req.post = await Post.findById(id); next(); });
Error middleware (4 args)
Express error handler takes (err, req, res, next) — must be declared after all routes.
Example: app.use((err, req, res, next) => { const status = err.status ?? 500; res.status(status).json({ error: err.message }); });
res.json() / res.status()
Send JSON response. Chain status code before json. res.sendFile for static files.
Example: return res.status(201).json({ id: newUser.id, message: 'Created' });
fetch() (Node 18+)
Native fetch in Node.js 18+ — no need for node-fetch or axios for basic requests.
Example: const data = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }).then(r => r.json());
Rate limiting middleware
Express-rate-limit — prevent abuse with configurable window/max per IP.
Example: app.use('/api/', rateLimit({ windowMs: 15*60*1000, max: 100 }));

Streams & Events

Readable / Writable / Transform
Three stream types. Pipe them: readable.pipe(transform).pipe(writable). Use pipeline() for error handling.
Example: await pipeline(fs.createReadStream(src), zlib.createGzip(), fs.createWriteStream(dest));
stream.pipeline() (util.promisify)
Promisified pipeline auto-cleans up on error. Replaces .pipe() for production use.
Example: import { pipeline } from 'node:stream/promises'; await pipeline(source, dest);
Readable.from(iterable)
Create readable stream from any sync/async iterable — generators, arrays, async generators.
Example: const stream = Readable.from(async function*() { for await (const row of db) yield row; }());
EventEmitter
Custom event bus. .on() / .once() / .off() / .emit(). setMaxListeners(0) for unlimited.
Example: class Queue extends EventEmitter { push(job) { this.emit('job', job); } }
events.once(emitter, event)
Promisified EventEmitter.once — await the next occurrence of an event.
Example: await events.once(server, 'listening'); console.log('Server ready');
AbortSignal.timeout(ms)
Create AbortSignal that automatically aborts after timeout — works with fetch, streams, child processes.
Example: await fetch(url, { signal: AbortSignal.timeout(5000) });

Worker Threads & Cluster

worker_threads
True CPU parallelism in Node — shared memory via SharedArrayBuffer, message passing.
Example: const { Worker, isMainThread, parentPort } = require('worker_threads');
workerData / parentPort
Pass initial data to worker at creation. parentPort.postMessage() sends results back.
Example: new Worker('./worker.js', { workerData: { items: chunk } })
cluster.fork()
Multi-process HTTP server — one process per CPU. OS load-balances connections across workers.
Example: if (cluster.isPrimary) { os.cpus().forEach(() => cluster.fork()); } else { app.listen(3000); }
jest / node --test
Node 18+ has built-in test runner (node:test). Jest needs config but has richer ecosystem.
Example: import { test, describe, it } from 'node:test'; import assert from 'node:assert';

Performance & Diagnostics

--inspect / Chrome DevTools
Start Node with --inspect or --inspect-brk then connect Chrome DevTools for full debugging.
Example: node --inspect-brk server.js # pause on first line
performance.now() / perf_hooks
High-resolution timing. performance.mark/measure for named profiling segments.
Example: const { performance, PerformanceObserver } = require('perf_hooks');
--prof / --prof-process
V8 CPU profiler. Run with --prof, process with --prof-process for flamegraph-ready output.
Example: node --prof app.js; node --prof-process isolate-*.log > processed.txt
v8.writeHeapSnapshot()
Write heap snapshot for memory leak analysis in Chrome DevTools Memory tab.
Example: process.on('SIGUSR2', () => { v8.writeHeapSnapshot(); });
NODE_ENV=production
Critical env var — Express disables error details, React strips dev warnings, many libs optimize.
Example: NODE_ENV=production node server.js
async_hooks / AsyncLocalStorage
Track async context across request lifecycle — request-scoped logging, tracing without thread-locals.
Example: const store = new AsyncLocalStorage(); store.run({ requestId: uuid() }, () => handler(req, res));