Node.jsPrintable

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.

Back to the Node.js tutorial

Basics

SyntaxWhat it doesLesson
node app.js node --watch app.jsRun a script, restart on changesIntroduction
export function f() {} import { f } from './f.js'ES modulesModules
import fs from 'node:fs/promises'Built-in module with the node: prefixModules
npm init -y npm install express npm i -D vitestCreate a project, add packagesnpm & Packages
npm run dev npm ci npx toolScripts, exact installs, one-off toolsnpm & Packages

Files, events & process

SyntaxWhat it doesLesson
await readFile(p, 'utf8') await writeFile(p, text)Read and write filesFile System
await mkdir(dir, { recursive: true }) readdir statFolders and file infoFile System
path.join(import.meta.dirname, 'data', 'x.json')Build a path next to the scriptpath & os
path.basename(p) path.extname(p) os.homedir()Take paths apart, system infopath & os
emitter.on('x', fn) emitter.emit('x', data) onceEventsEvents
process.env.PORT process.argv process.exitCode = 1Environment, arguments, exit codesprocess & env
node --env-file=.env app.jsLoad a .env fileprocess & env

Async patterns

SyntaxWhat it doesLesson
const data = await fn(); inside async functionWait for a promiseAsync Patterns
await Promise.all([a(), b()])Run independent tasks in parallelAsync Patterns
await Promise.allSettled(tasks)Collect every outcomeAsync Patterns
fetch(url, { signal: AbortSignal.timeout(3000) })Timeout an operationAsync Patterns
promisify(callbackFn)Callback API to promiseAsync Patterns

Web servers & Express

SyntaxWhat it doesLesson
createServer((req, res) => res.end('hi')).listen(3000)Built-in HTTP serverHTTP Server
app.get('/items/:id', (req, res) => res.json(item))Express routeExpress Basics
req.params req.query req.body with express.json()Read request dataExpress Basics
res.status(201).json(x) res.sendStatus(204)Status codes and responsesExpress Basics
const r = Router(); app.use('/api/items', r)RoutersExpress Routing
app.use((req, res, next) => { next(); })MiddlewareMiddleware
GET /items?page=2&limit=20 POST PATCH DELETEREST conventionsREST API
Schema.safeParse(req.body)Validate input with ZodValidation
app.use(express.static(dir)) res.render('page', data)Static files and templatesStatic Files & Templates
app.use((err, req, res, next) => { ... })Error-handling middlewareError Handling

Advanced Node

SyntaxWhat it doesLesson
await pipeline(createReadStream(a), createGzip(), createWriteStream(b))StreamsStreams
db.prepare('SELECT * FROM t WHERE id = ?').get(id)Prepared statementDatabases
await scryptAsync(password, salt, 64) timingSafeEqualHash and check passwordsAuthentication
res.cookie('sid', id, { httpOnly: true, secure: true })Secure session cookieAuthentication
helmet() cors({ origin: [...] }) rateLimit(...)Security middlewareSecurity
test('name', () => assert.equal(a, b)) node --testBuilt-in testsTesting
wss.on('connection', (ws) => ws.on('message', fn))WebSocketsWebSockets
new Worker(url, { workerData }) execFile(cmd, args)Workers and child processesProcesses & Workers
node --inspect app.js performance.now()Debug and measureDebugging & Performance
process.on('SIGTERM', () => server.close())Graceful shutdownDeployment

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 import needs "type": "module" in package.json or a .mjs extension. In ES modules, __dirname doesn't exist; build it from import.meta.url or use import.meta.dirname in recent versions.
  • Forgetting await. const data = fs.promises.readFile(file) gives you a Promise, not the file. Missing await is the most common async bug in Node.js code.
  • Sync methods block everyone. readFileSync is 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 read req.body, and the error handler with four arguments must come last.
  • Send one response only. Calling res.send twice, often because a return is 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.PORT is "3000", not 3000, and a missing variable is undefined. Convert and validate them when the app starts.
  • Never commit .env files. Add .env to .gitignore and keep an .env.example with 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