Node.js Cheat Sheet
Free Node.js cheat sheet: the most-used Node.js syntax and methods at a glance — searchable and beginner-friendly.
Modules & npm
| Concept | Syntax | Example |
|---|---|---|
| Import (ESM) Use ESM when package.json has "type": "module". | import x from "pkg" | import express from "express" |
| Require (CommonJS) The classic Node module system, default without "type": "module". | const x = require("pkg") | const fs = require("fs") |
| Export ESM uses export / export default instead. | module.exports / export default | module.exports = { add } |
| Init a project Creates package.json with default values. | npm init -y | npm init -y |
| Install packages -D saves to devDependencies. | npm install pkg | npm install express
npm install -D nodemon |
| Run a script Runs a command defined in package.json scripts. | npm run name | npm run start |
Core Modules (fs, path, http)
| Concept | Syntax | Example |
|---|---|---|
| Read a file (async) Promise-based file read; pass "utf8" to get a string. | fs.promises.readFile(path, enc) | const txt = await fs.promises.readFile("a.txt", "utf8") |
| Write a file Creates or overwrites the file with the given data. | fs.promises.writeFile(path, data) | await fs.promises.writeFile("out.txt", "hi") |
| Join paths Builds OS-correct paths; avoids manual slash juggling. | path.join(...segments) | path.join(__dirname, "data", "x.json") |
| File extension / base Parse parts of a path safely. | path.extname / path.basename | path.extname("a.txt") // ".txt" |
| Create a server The low-level HTTP server underneath frameworks. | http.createServer(handler) | http.createServer((req, res) => res.end("hi")).listen(3000) |
| Environment vars Read config from the environment with a sensible default. | process.env.NAME | const port = process.env.PORT || 3000 |
Async
| Concept | Syntax | Example |
|---|---|---|
| Promise Represents a future value; resolve on success, reject on error. | new Promise((resolve, reject) => ...) | const p = new Promise((res) => setTimeout(res, 100)) |
| async/await Write asynchronous code that reads top to bottom. | async function f() { await p } | async function load() {
const r = await fetch(url)
} |
| Error handling await rejections throw, so wrap them in try/catch. | try { await ... } catch (e) {} | try {
await save()
} catch (e) {
console.error(e)
} |
| Run in parallel Awaits multiple promises concurrently. | await Promise.all([...]) | const [a, b] = await Promise.all([f1(), f2()]) |
| Callback style The original Node pattern: error-first callbacks. | fn(args, (err, data) => {}) | fs.readFile("a.txt", (err, data) => { ... }) |
| Promisify a callback Wrap an error-first callback API as a promise. | util.promisify(fn) | const readFile = util.promisify(fs.readFile) |
Express Basics
| Concept | Syntax | Example |
|---|---|---|
| Create app The app object holds routes and middleware. | const app = express() | import express from "express"
const app = express() |
| Start listening Binds the server to a port. | app.listen(port, cb) | app.listen(3000, () => console.log("up")) |
| GET route Handler receives request and response objects. | app.get(path, handler) | app.get("/", (req, res) => res.send("Hello")) |
| Send a response json() sets the content type and serializes for you. | res.send() / res.json() | res.json({ ok: true }) |
| Set status Chain status() before send() or json(). | res.status(code) | res.status(404).json({ error: "not found" }) |
| Parse JSON body Built-in middleware that populates req.body from JSON. | app.use(express.json()) | app.use(express.json()) |
Express Routing & Middleware
| Concept | Syntax | Example |
|---|---|---|
| Route params Named segments land in req.params. | app.get("/u/:id", ...) | app.get("/users/:id", (req, res) => res.send(req.params.id)) |
| Query string Reads ?q=... values from the URL. | req.query | const term = req.query.q |
| Middleware Runs before handlers; call next() to continue. | app.use((req, res, next) => ...) | app.use((req, res, next) => { console.log(req.url); next() }) |
| Router module Group related routes, then app.use("/api", r). | express.Router() | const r = express.Router()
r.get("/", handler) |
| Error middleware Four args marks it as the error handler; register it last. | (err, req, res, next) => ... | app.use((err, req, res, next) => res.status(500).send("oops")) |
| Serve static files Serves files (HTML, CSS, images) from a folder. | express.static(dir) | app.use(express.static("public")) |
Common Patterns
| Concept | Syntax | Example |
|---|---|---|
| JSON parse / stringify Convert between JSON strings and JS objects. | JSON.parse / JSON.stringify | const obj = JSON.parse(text) |
| Event emitter Pub/sub pattern used throughout Node's APIs. | emitter.on(event, cb) | import { EventEmitter } from "events"
const e = new EventEmitter()
e.on("data", fn) |
| Fetch (Node 18+) Built-in HTTP client; no extra dependency needed. | await fetch(url) | const data = await (await fetch(url)).json() |
| CLI arguments Index 0 is node, 1 is the script, 2+ are your args. | process.argv | const name = process.argv[2] |
| Graceful exit Stop the process; 0 means success. | process.exit(code) | process.exit(1) // non-zero = error |
| Load .env The dotenv package loads variables from a .env file. | import "dotenv/config" | import "dotenv/config"
const key = process.env.API_KEY |