Node.js Cheat Sheet
Running Node, modules, npm, files, paths, events, env variables, async patterns, Express, middleware, validation, errors, streams, databases, auth, testing and deployment on one printable page.
Basics
| Syntax | What it does | Lesson |
|---|---|---|
node app.js node --watch app.js | Run a script, restart on changes | Introduction |
export function f() {} import { f } from './f.js' | ES modules | Modules |
import fs from 'node:fs/promises' | Built-in module with the node: prefix | Modules |
npm init -y npm install express npm i -D vitest | Create a project, add packages | npm & Packages |
npm run dev npm ci npx tool | Scripts, exact installs, one-off tools | npm & Packages |
Files, events & process
| Syntax | What it does | Lesson |
|---|---|---|
await readFile(p, 'utf8') await writeFile(p, text) | Read and write files | File System |
await mkdir(dir, { recursive: true }) readdir stat | Folders and file info | File System |
path.join(import.meta.dirname, 'data', 'x.json') | Build a path next to the script | path & os |
path.basename(p) path.extname(p) os.homedir() | Take paths apart, system info | path & os |
emitter.on('x', fn) emitter.emit('x', data) once | Events | Events |
process.env.PORT process.argv process.exitCode = 1 | Environment, arguments, exit codes | process & env |
node --env-file=.env app.js | Load a .env file | process & env |
Async patterns
| Syntax | What it does | Lesson |
|---|---|---|
const data = await fn(); inside async function | Wait for a promise | Async Patterns |
await Promise.all([a(), b()]) | Run independent tasks in parallel | Async Patterns |
await Promise.allSettled(tasks) | Collect every outcome | Async Patterns |
fetch(url, { signal: AbortSignal.timeout(3000) }) | Timeout an operation | Async Patterns |
promisify(callbackFn) | Callback API to promise | Async Patterns |
Web servers & Express
| Syntax | What it does | Lesson |
|---|---|---|
createServer((req, res) => res.end('hi')).listen(3000) | Built-in HTTP server | HTTP Server |
app.get('/items/:id', (req, res) => res.json(item)) | Express route | Express Basics |
req.params req.query req.body with express.json() | Read request data | Express Basics |
res.status(201).json(x) res.sendStatus(204) | Status codes and responses | Express Basics |
const r = Router(); app.use('/api/items', r) | Routers | Express Routing |
app.use((req, res, next) => { next(); }) | Middleware | Middleware |
GET /items?page=2&limit=20 POST PATCH DELETE | REST conventions | REST API |
Schema.safeParse(req.body) | Validate input with Zod | Validation |
app.use(express.static(dir)) res.render('page', data) | Static files and templates | Static Files & Templates |
app.use((err, req, res, next) => { ... }) | Error-handling middleware | Error Handling |
Advanced Node
| Syntax | What it does | Lesson |
|---|---|---|
await pipeline(createReadStream(a), createGzip(), createWriteStream(b)) | Streams | Streams |
db.prepare('SELECT * FROM t WHERE id = ?').get(id) | Prepared statement | Databases |
await scryptAsync(password, salt, 64) timingSafeEqual | Hash and check passwords | Authentication |
res.cookie('sid', id, { httpOnly: true, secure: true }) | Secure session cookie | Authentication |
helmet() cors({ origin: [...] }) rateLimit(...) | Security middleware | Security |
test('name', () => assert.equal(a, b)) node --test | Built-in tests | Testing |
wss.on('connection', (ws) => ws.on('message', fn)) | WebSockets | WebSockets |
new Worker(url, { workerData }) execFile(cmd, args) | Workers and child processes | Processes & Workers |
node --inspect app.js performance.now() | Debug and measure | Debugging & Performance |
process.on('SIGTERM', () => server.close()) | Graceful shutdown | Deployment |
How to use this Node.js cheat sheet
This Node.js cheat sheet collects the code you'll reach for most often, in the same order as the course: running Node, modules, npm, files and paths, events, environment variables, async patterns, http and Express, middleware, validation, errors, streams, databases, authentication, testing, WebSockets, workers and deployment. Each row links to the lesson that explains it with examples and common mistakes.
Keep it open while you build. When you can't remember how to read a JSON body, mount a router, run a prepared statement or handle SIGTERM, a quick look here is faster than a search. Type part of a keyword into the filter box to jump straight to it, or print the page and keep it beside your keyboard.
Node.js gotchas worth remembering
- CommonJS and ES modules don't mix freely. A file using
importneeds"type": "module"in package.json or a.mjsextension. In ES modules,__dirnamedoesn't exist; build it fromimport.meta.urlor useimport.meta.dirnamein recent versions. - Forgetting await.
const data = fs.promises.readFile(file)gives you a Promise, not the file. Missingawaitis the most common async bug in Node.js code. - Sync methods block everyone.
readFileSyncis fine in a script that runs once, but inside a web server it pauses every request until the file is read. - Express middleware order matters.
app.use(express.json())must come before the routes that readreq.body, and the error handler with four arguments must come last. - Send one response only. Calling
res.sendtwice, often because areturnis missing after an early response, causes "Cannot set headers after they are sent". - Unhandled rejections crash the process. In Express 4, an error thrown inside an async route isn't caught automatically. Catch it and call
next(err), or use Express 5, which handles rejected promises for you. - Environment variables are strings.
process.env.PORTis"3000", not 3000, and a missing variable isundefined. Convert and validate them when the app starts. - Never commit .env files. Add
.envto .gitignore and keep an.env.examplewith the variable names but no real secrets.
Which sections to learn first
You don't need every line of this sheet to build something useful. Start with modules, npm scripts, reading and writing files with fs/promises, and an Express app with a few routes and express.json(). That's enough to build a small REST API. Streams, worker threads, WebSockets and deployment are powerful, but you'll reach for them once an app needs them, so treat those sections as a reference to return to rather than something to learn by heart on day one.
A quick revision routine
Pick one section a day and type each snippet into a file and run it with node. Seeing real output fixes the syntax in your memory far better than reading, and the Node.js exercises give you more practice on any section that still feels shaky.
The Node.js lessons behind this cheat sheet
Beginner
Intermediate
Advanced
Runtime and network references
Tools and application boundaries
- 35Node.js Interactive Readline CLIs
- 36Node.js Package Exports and Imports
- 37Node.js AsyncLocalStorage Request Context
- 38Node.js Web Streams Interoperability
- 39Node.js HTTP/2 Sessions and Streams
- 40Node.js Native TypeScript Type Stripping
- 41Node.js Permission Model
- 42Node.js Bounded File Uploads
- 43Node.js Diagnostics Channel Instrumentation