Node.js Cheat Sheet
Covers CommonJS and ES module syntax, filesystem operations, async patterns, the built-in HTTP server, and core Node.js globals.
CommonJS & ES Modules
The two module systems Node.js supports.
// CommonJS (default in .js unless package.json has "type": "module")const fs = require('fs');module.exports = { greet };function greet(name) { return `Hi ${name}`; }// ES Modules (package.json "type": "module", or .mjs extension)import fs from 'fs';export function greet(name) { return `Hi ${name}`; }export default greet;
Filesystem & Async Patterns
Reading files and working with streams and events.
const fs = require('fs/promises');async function readConfig() { const data = await fs.readFile('config.json', 'utf8'); return JSON.parse(data);}// Streams for large filesconst { createReadStream, createWriteStream } = require('fs');createReadStream('input.txt').pipe(createWriteStream('output.txt'));// EventEmitter patternconst { EventEmitter } = require('events');const emitter = new EventEmitter();emitter.on('data', (chunk) => console.log(chunk));emitter.emit('data', 'hello');
Built-in HTTP Server
Creating a server without a framework.
const http = require('http');const server = http.createServer((req, res) => { if (req.url === '/health' && req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'ok' })); return; } res.writeHead(404); res.end('Not found');});server.listen(3000, () => console.log('Listening on 3000'));
Core Modules & Globals
Frequently used built-ins.
- process.env- access environment variables
- process.argv- command-line arguments passed to the script
- __dirname / __filename- CommonJS-only globals for the current module's directory and file path
- path.join() / path.resolve()- cross-platform path construction
- Buffer- handles raw binary data
- child_process.spawn() / exec()- run external commands from within Node
- event loop phases- timers, pending callbacks, poll, check, and close callbacks, in that order
worker_threads for CPU-Bound Work
Offload blocking computation to a separate thread without forking a whole process.
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');if (isMainThread) { const worker = new Worker(__filename, { workerData: { n: 40 } }); worker.on('message', (result) => console.log('fib:', result)); worker.on('error', (err) => console.error(err)); worker.on('exit', (code) => console.log('worker exited', code));} else { function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); } parentPort.postMessage(fib(workerData.n));}
Multi-Core Scaling with cluster
Fork one worker process per CPU core to use all available cores for an HTTP server.
const cluster = require('cluster');const http = require('http');const os = require('os');if (cluster.isPrimary) { const cpuCount = os.cpus().length; for (let i = 0; i < cpuCount; i++) cluster.fork(); cluster.on('exit', (worker, code) => { console.log(`worker ${worker.process.pid} died (${code}), restarting`); cluster.fork(); });} else { http.createServer((req, res) => res.end(`Handled by PID ${process.pid}`)).listen(3000);}
stream.pipeline & Transform Streams
Compose streams safely with automatic error propagation and cleanup, avoiding manual .pipe() error handling.
const { pipeline, Transform } = require('stream');const { createReadStream, createWriteStream } = require('fs');const zlib = require('zlib');const upperCase = new Transform({ transform(chunk, encoding, callback) { callback(null, chunk.toString().toUpperCase()); }});pipeline( createReadStream('input.txt'), upperCase, zlib.createGzip(), createWriteStream('output.txt.gz'), (err) => { if (err) return console.error('Pipeline failed:', err); console.log('Pipeline succeeded'); });
Process Lifecycle & Graceful Shutdown
Events every production Node service should handle explicitly.
- process.on('SIGTERM', fn)- sent by orchestrators (Docker, Kubernetes) to request a graceful shutdown
- process.on('SIGINT', fn)- sent on Ctrl+C in a terminal
- process.on('uncaughtException', fn)- last-resort handler for synchronous errors that escaped all try/catch; log and exit, don't resume
- process.on('unhandledRejection', fn)- fires when a Promise rejects with no .catch(); treat as fatal in modern Node
- process.on('beforeExit', fn)- fires when the event loop has no more work, but before final exit; async work can still be scheduled here
- process.on('exit', fn)- fires synchronously at final shutdown; only synchronous cleanup is possible
- server.close(callback)- stops accepting new connections and lets in-flight requests finish before shutdown
Request-Scoped Context with AsyncLocalStorage
Propagate a request ID or user context through async calls without threading it through every function argument.
const { AsyncLocalStorage } = require('async_hooks');const als = new AsyncLocalStorage();function requestMiddleware(req, res, next) { const store = new Map(); store.set('requestId', crypto.randomUUID()); als.run(store, next);}function logWithContext(message) { const store = als.getStore(); console.log(`[${store?.get('requestId')}] ${message}`);}// Anywhere downstream in the same async chain, without passing req:async function handler() { logWithContext('processing started');}
Prefer the fs/promises API with async/await over callback-based fs methods: it composes cleanly with try/catch and avoids callback nesting, and Node has shipped it as stable since version 14.