Node.js Cheat Sheet
Quick reference from FreeCodingCourses.com
Modules
import { readFile } from 'node:fs/promises'- ES module import ("type": "module" in package.json).
export function add(a, b) { ... }- named export.
export default app- default export.
const fs = require('fs')- CommonJS import (the older default).
module.exports = add- CommonJS export.
npm and package.json
npm init -y- create a package.json with defaults.
npm install express- add a dependency.
npm install -D vitest- add a dev-only dependency.
npm run dev- run a script from package.json "scripts".
npx <tool>- run a package binary without installing it globally.
npm ci- clean, reproducible install from package-lock.json.
Files and paths
import { readFile, writeFile } from 'node:fs/promises'- the promise-based fs API.
const text = await readFile('a.txt', 'utf8')- read a file as a string.
await writeFile('out.txt', text)- write (overwrites).
import path from 'node:path'- build paths that work on any OS.
path.join(dir, 'sub', 'file.txt')- join path parts safely.
Environment and process
process.env.DATABASE_URL- read an environment variable.
process.argv.slice(2)- command-line arguments passed to your script.
process.exit(1)- exit with a non-zero (error) code.
process.cwd()- current working directory.
A minimal HTTP server (no dependencies)
import { createServer } from 'node:http'- built in, nothing to install.
createServer((req, res) => { res.end('Hello') }).listen(3000)- respond to every request and listen on port 3000.
The same server in Express
import express from 'express'- after npm install express.
const app = express()- create the app.
app.get('/', (req, res) => res.send('Hello'))- handle GET /.
app.use(express.json())- parse JSON request bodies.
app.listen(3000)- start listening.
Unlock the full Node.js cheat sheet
You're seeing 2 of 6 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.