Frameworks
Server-side JavaScript from the first script to threads, streams and production debugging.
A complete path through Node.js: modules and npm, async programming and the event loop, files, CLIs, HTTP APIs, databases, testing, and finally threads, streams and debugging in production. Each subject links the official documentation.
The subjects follow the roadmap.sh Node.js roadmap.
Node.js runs JavaScript outside the browser: V8 for the language, libuv for the event loop and non-blocking I/O, and a standard library for files, networks and processes. Know what it is good at (I/O-heavy servers, tooling, CLIs) and what it is not (long CPU-bound work on the main thread).
A runtime, not a framework or a language: V8 plus libuv plus built-in modules, running one JavaScript thread that hands slow I/O to the operating system.
One language across client and server, a huge package registry, and an event-driven model that holds thousands of idle connections cheaply. Pick it for APIs, real-time apps and tooling; reach for worker threads or another runtime for heavy number crunching.
Released by Ryan Dahl in 2009, forked as io.js in 2014 and merged back under the OpenJS Foundation. Today even-numbered releases become LTS — know which line you are on and when it reaches end of life.
Same language, different host: no window or DOM, but process, Buffer, the file system and sockets. You control the runtime version, so new syntax is safe to use without transpiling for old clients.
Run a file with node app.js, open a REPL with node, evaluate with node -e, and run TypeScript directly in recent versions with type stripping. --env-file loads a .env without any package.
Every file is a module with its own scope. Node supports two systems — CommonJS and ES modules — and decides which one a file uses from its extension and the nearest package.json "type". Understanding how resolution and interop work saves hours of "cannot use import outside a module".
require() and module.exports: synchronous, cached after the first load, with __dirname available. Still the default for .js files without "type": "module".
import/export, top-level await, static analysis and tree shaking. Use .mjs or "type": "module"; importing CommonJS works, and recent Node versions can also require() an ES module.
Export a small public surface, import by relative path or package name, and use the exports field in package.json to control which files consumers may reach.
globalThis (and its Node alias global) holds what every module can see — process, Buffer, timers. Adding your own globals hides dependencies; prefer explicit imports.
npm is the package manager and registry that ships with Node. Learn how dependencies are declared, how version ranges and the lockfile keep installs reproducible, and how scripts turn package.json into the project's task runner.
Runs a package binary without installing it globally — the local one from node_modules/.bin if present, otherwise a temporary download.
npm install -g puts CLIs on your PATH for every project. Keep it for tools, never for libraries a project imports — those belong in its own dependencies.
Dependencies live in the project's node_modules; dependencies ship to production, devDependencies are build and test tools. Commit package-lock.json and install with npm ci in CI.
MAJOR.MINOR.PATCH: breaking, feature, fix. ^1.4.0 accepts any 1.x from 1.4.0; ~1.4.0 only patches. The lockfile pins what was actually installed.
npm outdated shows what is behind, npm update moves within your ranges, and a major bump is a deliberate edit to package.json followed by reading the changelog. npm audit flags known vulnerabilities.
The scripts field is the project's command list: npm run build, npm test, with pre/post hooks and node_modules/.bin on the PATH.
Several packages in one repository, installed together and linked to each other — the built-in way to run a small monorepo.
A publishable package needs a name, a version, entry points in exports, a files allow-list and types if you ship TypeScript. npm pack --dry-run shows exactly what would be published.
Errors in Node arrive in four ways: thrown synchronously, passed to a callback, rejected from a promise, or emitted as an error event. Each needs its own handling, and anything left uncaught takes the process down. Separate operational errors you can recover from (a missing file, a timed-out request) from programmer errors you should crash on.
The language's own classes — TypeError, RangeError, SyntaxError, ReferenceError — all inherit from Error and carry message, stack and an optional cause.
Raised when the operating system refuses something: ENOENT, EACCES, ECONNREFUSED, EADDRINUSE. Branch on error.code, never on the message text.
Subclass Error for your domain (NotFoundError, ValidationError), set a stable code, and wrap low-level failures with { cause } so the original stack survives.
The node:assert module throws AssertionError when an invariant fails — useful in tests and for guarding states that should be impossible.
process.on('uncaughtException') and 'unhandledRejection' are last-chance hooks for logging, not recovery: the process is in an unknown state, so log, flush and exit, and let a supervisor restart it.
Wrap await in try/catch, always return or await promises so rejections propagate, attach error listeners to emitters and streams, and use pipeline() so one failing stream tears down the rest.
A stack trace shows the frames that led to an error. Async gaps used to cut it short; V8's async stack traces now stitch awaited calls together, and Error.stackTraceLimit controls the depth.
Start with node --inspect (or --inspect-brk to pause on the first line), attach Chrome DevTools or your editor, and set breakpoints instead of scattering console.log.
Node's single thread stays responsive by never waiting: I/O is started, and the result comes back later through a callback, a promise or an event. Master the progression from callbacks to promises to async/await, and know exactly when each kind of queued work runs in the event loop.
Node's original convention: the last argument is (err, result) => {}, error first. Simple, but nesting them gets unreadable — util.promisify converts them to promises.
An object for a value that arrives later. Chain with .then, combine with Promise.all, allSettled, race and any; most core modules have a promise API under node:fs/promises and friends.
Promise code that reads top to bottom. Run independent awaits concurrently with Promise.all instead of one after another, and remember an async function always returns a promise.
The publish/subscribe base class behind streams, servers and sockets: on, once, emit, off. An emitted error with no listener throws, and events.once() turns an event into a promise.
libuv's loop cycles through phases — timers, pending callbacks, poll for I/O, check (setImmediate), close — draining the nextTick and microtask queues between each callback. Block it and every request waits.
Runs a callback after at least the given delay, in the timers phase. The delay is a minimum, not a promise; node:timers/promises gives an awaitable version.
Repeats a callback every interval until clearInterval. Intervals do not wait for async work to finish — for jobs that may overrun, schedule the next run with setTimeout at the end of each one.
Queues a callback for the check phase, right after the current poll phase — the way to yield to pending I/O before continuing long work.
Runs before any other queued work, even promise callbacks. Handy for emitting events after a constructor returns; recursive use starves I/O, so prefer queueMicrotask for ordinary deferral.
Reading, writing and watching files is everyday Node work. Use the promise-based fs API, build paths with path rather than string concatenation, and stream anything large instead of loading it into memory.
The directory of the current CommonJS module. In ES modules use import.meta.dirname (or derive it from import.meta.url).
The absolute path of the current CommonJS module; import.meta.filename is the ESM equivalent.
The directory the process was started from — not where the file lives. Resolve user-supplied paths against it, and paths to your own assets against __dirname.
join, resolve, dirname, basename, extname — cross-platform path handling, so Windows backslashes never break your code.
Read, write, append, stat, mkdir with recursive, rm and watch. Prefer fs/promises; the *Sync versions block the event loop and belong only in startup code and scripts.
Match files by pattern like src/**/*.ts. Node now ships fs.glob; the glob package remains the widely used option for older versions.
A friendlier glob wrapper: multiple patterns, negation and .gitignore support out of the box.
Adds copy, move, ensureDir, outputJson and friends on top of fs — less needed now that core has cp and recursive mkdir, but still common.
Reliable file watching across platforms, smoothing over fs.watch quirks — what most dev servers and build tools use underneath.
Node is excellent for CLIs: read arguments and environment variables, prompt for input, print readable output and exit with a meaningful code. A good CLI composes with others — it writes data to stdout, diagnostics to stderr, and fails with a non-zero code.
The raw argument array: the node binary, the script path, then the user's arguments. util.parseArgs parses flags without a dependency.
The standard library for real CLIs: subcommands, typed options, defaults and generated --help.
Environment variables as strings. Read and validate them once at startup into a typed config object, and never commit their values.
Loads a .env file into process.env for local development. Recent Node versions do this natively with --env-file or process.loadEnvFile().
A readable stream of what is piped or typed in. Combine with readline to read line by line, or consume it whole when your tool is a filter in a pipe.
Lightweight interactive prompts — text, confirm, select — with validation and promise-based answers.
The most widely used prompt library, now split into small @inquirer/* prompts you import one at a time.
Results go to stdout so they can be piped; logs, progress and errors go to stderr. Check process.stdout.isTTY before printing colours or spinners.
Terminal colours and styles with automatic colour-support detection. Core util.styleText now covers the basics without a dependency.
Big ASCII-art banners for a CLI's welcome screen — fun, purely cosmetic.
Progress bars for long-running tasks, single or multiple, redrawn in place on stderr.
Zero means success, anything else failure. Set process.exitCode and let the loop drain rather than calling process.exit(), which can cut off pending writes.
The heart of most Node work: serving HTTP and calling other services. Learn the raw http module once so frameworks stop being magic, pick a framework that fits the project, and handle authentication, timeouts and retries properly on both sides.
http.createServer((req, res) => …): the request is a readable stream, the response a writable one. Every framework is built on this.
The minimal, middleware-based framework most of the ecosystem grew up on. Express 5 forwards rejected promises from async handlers to your error middleware.
A fast framework built around JSON-schema validation and serialisation, an encapsulated plugin system and first-class TypeScript.
An opinionated, Angular-style framework: modules, dependency injection, decorators, guards and pipes — structure for large teams, on top of Express or Fastify.
A tiny framework on Web-standard Request/Response, so the same app runs on Node, Bun, Deno and edge runtimes.
The browser's fetch is built into Node (powered by undici). Add AbortSignal.timeout() to every call and check response.ok — fetch does not throw on 4xx/5xx.
A promise-based HTTP client with interceptors, automatic JSON and errors on non-2xx statuses — still common in older codebases.
A small wrapper over fetch that adds retries, timeouts, hooks and throwing on HTTP errors.
A full-featured Node HTTP client with retries, pagination, streams and hooks.
Signs and verifies JWTs. Keep access tokens short-lived, pin the accepted algorithm on verify, and never put secrets in the payload — it is only encoded, not encrypted.
Authentication middleware with hundreds of strategies — local passwords, OAuth providers, JWT — plugged into Express-style apps.
Restart the app automatically whenever a source file changes, so the edit-run loop takes a second. Node now does this natively; nodemon remains for older versions and custom setups.
Server-rendered HTML from data, without a front-end framework. Still the simplest way to build emails, admin pages and small sites; always rely on the engine's escaping to avoid XSS.
Plain HTML with <%= %> tags for escaped output — nothing new to learn if you know HTML and JavaScript.
Indentation-based templates with mixins and inheritance — very terse, with its own syntax to learn.
A UI language that streams HTML from the server and hydrates only the interactive parts.
Most services are a thin layer over a database. Learn one native driver well enough to write parameterised SQL and manage a connection pool, then choose a query builder or ORM for productivity — knowing what SQL it generates.
The low-level clients — pg for PostgreSQL, mysql2, the official MongoDB driver. Always pass values as parameters, never by string concatenation, and reuse one pool per process.
A schema-first ORM: describe models in schema.prisma, get a fully typed client and generated migrations.
A TypeScript ORM that reads like SQL — schemas in code, typed queries, almost no runtime overhead.
A decorator-based ORM with entities, repositories and migrations, popular alongside NestJS.
A long-established promise-based ORM for Postgres, MySQL, SQLite and MSSQL.
A SQL query builder with migrations and seeds — composable SQL without a full ORM.
Schemas, validation, middleware and population on top of MongoDB.
Fast unit tests for logic, integration tests against a real database, and a few end-to-end tests through a browser. Node now has a capable built-in runner, so a dependency-free test setup is a real option.
The built-in runner: node --test, describe/it, mocks, timers, snapshots and coverage — no dependencies.
A fast, Vite-powered runner with a Jest-compatible API and native ESM and TypeScript support.
The long-time default: all-in-one runner, assertions, mocks and snapshots.
End-to-end tests in real Chromium, Firefox and WebKit, with auto-waiting, tracing and API testing.
Browser end-to-end and component tests with a time-travelling interactive runner.
Production logs are for machines first: structured JSON, levels, request ids for correlation, and no secrets or personal data. Log to stdout and let the platform ship it.
A crashed Node process should come back on its own. Use a process manager or the platform (systemd, Docker restart policies, Kubernetes), and shut down gracefully on SIGTERM: stop accepting work, finish in-flight requests, close the pools.
A production process manager: restarts on crash, cluster mode across CPU cores, zero-downtime reloads, log management.
JavaScript runs on one thread, but a Node app does not have to. Spread load across cores with cluster, move CPU-heavy work to worker threads, and run other programs with child processes — each with a different cost and isolation level.
spawn, exec and execFile run other programs; fork starts another Node process with an IPC channel. Never pass user input through a shell.
Forks one worker process per core, all sharing a server port. Workers share no memory — sessions and caches must live elsewhere.
Real threads in the same process for CPU-bound JavaScript — hashing, image work, parsing — talking by messages or SharedArrayBuffer. Use a pool rather than one worker per task.
Process data piece by piece instead of all at once: readable, writable, duplex and transform streams with backpressure built in. stream.pipeline connects them and cleans up on failure, and readables are async iterables you can for await over. Essential for large files, uploads and proxies.
Beyond breakpoints: find why memory grows, why CPU is pegged, and why production is slow. Learn heap snapshots, CPU profiles and an APM, and reproduce problems locally with the same flags.
Opens the V8 inspector so Chrome DevTools or VS Code can attach: breakpoints, CPU profiles and heap snapshots on a running process.
Usually something that keeps growing: a cache without a limit, listeners never removed, closures holding big objects. Compare heap snapshots over time to find what is retained.
V8 collects young objects often and cheaply and old ones less often. --max-old-space-size sets the heap limit; GC traces show whether pauses are hurting latency.
Application performance monitoring traces requests across services and shows slow endpoints and queries in production. OpenTelemetry is the vendor-neutral way to instrument.
Before adding a dependency, check the standard library: crypto for hashing and random ids, os, url and URLSearchParams, util, zlib, events, readline, assert, timers/promises and node:sqlite. Import them with the node: prefix so they are never confused with npm packages.