Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 133 ยท Practice and Review

Node.js Cheat Sheet

A practical Node.js 24 cheat sheet with runnable recipes for core modules, the event loop order, files and streams, HTTP, async patterns, error codes and common commands.

This page is the one you keep open in a second tab. It collects the things you look up again and again: the command line flags, what each core module is for, the order in which callbacks run, short recipes for files, streams, HTTP and async code, and the error codes you will meet. It does not explain ideas from scratch. Each section links to the lesson that does.

Every code block that has an editor is a complete program you can run and change. Everything runs on Node.js 24 as an ES module unless the first line says // cjs. Where the output would differ from machine to machine (ports, times, random values) the examples print only things that are the same on every run.

Running Node

These commands are shown read-only, because the editor starts the program for you. See running code for the details.

Terminal
node app.mjs                 # run a file
node -e "console.log(1 + 1)" # run a string
node -p "process.version"    # run and print the result
node                         # start the REPL (type .help)
node --watch app.mjs         # restart when imported files change
node --env-file=.env app.mjs # load environment variables from a file
node --run build             # run the "build" script from package.json
node --test                  # run all test files with node:test
node --check app.mjs         # syntax check only
node --max-old-space-size=512 app.mjs   # heap limit in MB
node --inspect app.mjs       # debugger (Chrome DevTools / VS Code)
node --import ./setup.mjs app.mjs       # preload a module

Useful process facts: process.argv (the first two items are the Node binary and your script), process.env.NAME, process.exitCode = 1 (preferred over process.exit(1), which can cut off pending output), process.cwd(), process.on('SIGTERM', ...), process.memoryUsage(), process.hrtime.bigint() for timing. See process.

Core modules at a glance

Module Use it for Typical import
node:fs/promises Read, write, list and delete files import { readFile } from 'node:fs/promises'
node:fs Streams and the sync / callback forms import { createReadStream } from 'node:fs'
node:path Building and parsing file paths import path from 'node:path'
node:os Temp folder, platform, EOL import { tmpdir } from 'node:os'
node:url URL, fileURLToPath, pathToFileURL global URL needs no import
node:events EventEmitter, once, on import { EventEmitter } from 'node:events'
node:stream and stream/promises Streams and pipeline import { pipeline } from 'node:stream/promises'
node:buffer Binary data (Buffer is also global) Buffer.from('hi')
node:http, node:https Servers and low-level clients import http from 'node:http'
node:net, node:dgram, node:dns TCP, UDP, name lookups import net from 'node:net'
node:crypto Hashes, HMAC, random, encryption import { createHash } from 'node:crypto'
node:zlib gzip, deflate, brotli import { gzipSync } from 'node:zlib'
node:util promisify, inspect, parseArgs, format import { parseArgs } from 'node:util'
node:assert Assertions for scripts and tests import assert from 'node:assert/strict'
node:test The built-in test runner import test from 'node:test'
node:worker_threads CPU work off the main thread import { Worker } from 'node:worker_threads'
node:child_process Run other programs import { execFile } from 'node:child_process'
node:readline Line-by-line input import readline from 'node:readline'
node:timers/promises setTimeout as a promise import { setTimeout as sleep } from 'node:timers/promises'
node:sqlite Built-in SQLite (experimental in 24) import { DatabaseSync } from 'node:sqlite'

Always write the node: prefix. It makes it obvious that a name is built in, and it cannot be shadowed by an npm package. The next program is a tour of small calls from the modules above, with their results: paths, URL, Buffer, hashing, events, util, parseArgs, gzip, assertions and a few modern helpers.

Node.js A tour of core modules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Things to notice: path.join normalizes ..; path.resolve always gives an absolute path; hรฉllo is 6 bytes in UTF-8 because รฉ takes two; parseArgs returns an object with a null prototype, which is why it prints as [Object: null prototype]; Object.groupBy does the same. assert.equal failing carries the code ERR_ASSERTION. More in path and os, util, buffers and crypto hashing.

Modules: ESM versus CommonJS

ES modules (.mjs, or "type": "module") CommonJS (.cjs, default for .js)
Import import fs from 'node:fs' const fs = require('node:fs')
Export export const a = 1; export default f; module.exports = { a }
Top-level await Yes No
Current file import.meta.filename, import.meta.dirname __filename, __dirname
Load JSON import data from './a.json' with { type: 'json' } require('./a.json')
Load the other kind import cjs from './a.cjs' (works) require('./a.mjs') (works in Node 22.12+ unless the module uses top-level await)

ESM is the default choice for new code; see ES modules, CommonJS and ESM and CJS interop.

The event loop: who runs first

Node runs your script, then repeatedly goes round the event loop. Each round has phases, and between callbacks Node drains two queues of small tasks.

Phase or queue What runs there
Microtasks Promise reactions (.then, await continuations), queueMicrotask
process.nextTick queue Callbacks scheduled with process.nextTick
Timers setTimeout and setInterval callbacks that are due
Pending callbacks Some deferred system callbacks
Poll I/O callbacks (file reads, sockets); waits here for new I/O
Check setImmediate callbacks
Close callbacks close events such as socket.on('close')

The first program shows the order for a plain script. Run it, and then read the explanation below.

Node.js Order of microtasks in an ES module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In an ES module, the whole file runs as part of a promise job, so the microtask queue is drained first and process.nextTick runs after it. In a CommonJS file the order is the other way round, as the same program with // cjs on the first line shows:

Node.js The same program as CommonJS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The practical rules: synchronous code finishes first; await and .then continuations come next; nextTick callbacks jump the queue in CommonJS; timers and immediates come after all of that. You cannot rely on the order of setTimeout(fn, 0) against setImmediate in the main script (it depends on how fast the process started), but inside an I/O callback setImmediate always wins:

Node.js Immediate or timeout inside an I/O callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Never write a recursive process.nextTick loop: the nextTick queue is drained completely before the event loop moves on, so such a loop starves I/O. See the event loop and timers.

Files and streams

Use node:fs/promises for whole files and streams for big ones. The recipes below create a temporary folder, so they are safe to run. They cover write, append, read, JSON, listing a tree, stat, rename, an existence check, reading lines, gzip with pipeline, a one-expression Transform, and the error you will meet most often.

Node.js File and stream recipes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Remember: readdir has { recursive: true }; there is no fs.exists in the promise API (use access in a try/catch, or better, just attempt the operation and handle ENOENT); pipeline closes every stream if one fails, unlike chained .pipe() calls; and JSON.parse of a file is only safe for files you trust in size. See fs promises, directories, file streams and pipeline and backpressure.

HTTP in a few lines

Create a server with http.createServer, read the body as an async iterable, and set the status and headers before end. Call it with the built-in fetch. The program below does a GET with a query string, a POST with JSON, a 404, a redirect handled both ways, and an immediately aborted request. It uses 127.0.0.1 and port 0, so the operating system picks a free port; there is no outside network in the editor.

Node.js A server and fetch in one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that fetch does not reject on a 404 or 500: check response.ok or response.status yourself. It only rejects on network failures and aborts. Always set a timeout in real code (AbortSignal.timeout(5000)).

Status Meaning When to use
200 / 201 / 204 OK / Created / No content Success; new resource; success with no body
301 / 302 / 304 Moved / Found / Not modified Redirects and cache validation
400 / 401 / 403 Bad request / Unauthenticated / Forbidden Invalid input; no login; no permission
404 / 405 / 409 / 422 Not found / Method not allowed / Conflict / Unprocessable Missing route or resource; wrong method; duplicate; failed validation
429 Too many requests Rate limiting
500 / 502 / 503 / 504 Server error / Bad gateway / Unavailable / Gateway timeout Your bug; a bad upstream; overload; slow upstream

More in HTTP server, HTTP client, request bodies and REST APIs.

Async recipes

These small helpers appear in nearly every project: retry with backoff (keeping the original error as cause), a concurrency limit that returns results in input order, a timeout wrapper, a promise you resolve from outside, allSettled and any, cancellation with AbortController and a debounce.

Node.js Async recipes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The limit helper starts limit workers that share a counter, so at most two tasks ran at once (peak concurrency: 2) and results[i] keeps the input order even though tasks finish in any order. Promise.race for a timeout does not cancel the slow work, it only stops waiting for it; pass an AbortSignal to the real operation when you can. See promises, async/await, abort signals and concurrency control.

package.json and npm

These are read-only; the editor has no npm packages installed.

Terminal
npm init -y                  # create package.json
npm install express          # add a dependency
npm install -D vitest        # add a dev dependency
npm ci                       # clean install from the lockfile (CI, deploys)
npm run build                # run a script
npm test                     # run the "test" script
npm outdated                 # what could be updated
npm audit                    # known vulnerabilities
npx some-tool                # run a package binary without installing it globally
JSON
{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module",
  "engines": { "node": ">=24" },
  "exports": { ".": "./src/index.js" },
  "scripts": { "start": "node src/server.js", "test": "node --test" },
  "dependencies": {},
  "devDependencies": {}
}

"type": "module" makes .js files ES modules, exports defines what other code may import from your package, and engines documents (and with engine-strict, enforces) the Node version. See package.json.

Error codes you will meet

Node errors carry a string code. Test error.code, not the message text.

Code Meaning Typical cause
ENOENT No such file or directory Wrong path, missing file, wrong working directory
EEXIST File already exists mkdir without recursive, or exclusive create
EACCES, EPERM Permission denied File mode, protected folder
EISDIR, ENOTDIR Directory used as file, or the reverse Reading a folder
EMFILE Too many open files Opening thousands of files at once
EADDRINUSE Port already in use Another process listens on it
ECONNREFUSED Nothing listens at that address Server not started or wrong port
ECONNRESET Other side dropped the connection Crash, timeout, abrupt close
ETIMEDOUT Connection attempt timed out Network or firewall
EPIPE Wrote to a closed pipe or socket Reader quit early
ERR_MODULE_NOT_FOUND An import could not be resolved Typo, missing file extension in ESM
ERR_UNHANDLED_ERROR 'error' event with no listener Add emitter.on('error', ...)

See errors for how to create, chain and handle them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In an ES module, which of these runs first after the synchronous code finishes?

    An ES module runs inside a promise job, so the microtask queue is drained before the nextTick queue. In CommonJS the nextTick queue goes first.
  2. 2. Inside a file-read callback, what is the order of setTimeout(fn, 0) and setImmediate(fn)?

    After the poll phase where I/O callbacks run, the loop goes to the check phase (setImmediate) before it returns to the timers phase.
  3. 3. What does fetch do when the server answers with status 404?

    fetch only rejects for network problems and aborts. HTTP error statuses are normal responses, so check response.ok or response.status.
  4. 4. Which is the better way to set a failing exit status for a script?

    Setting process.exitCode lets pending output flush and the process end normally. process.exit(1) stops immediately and can cut off writes.
  5. 5. What does the error code ECONNREFUSED tell you?

    ECONNREFUSED means the connection attempt was rejected, usually because the server is not running or the port is wrong. EADDRINUSE is the opposite problem, on the listening side.

Summary

  • Prefix built-in modules with node:; use fs/promises, timers/promises and stream/promises for promise-based code.
  • Microtasks run before timers, and ES modules drain promises before nextTick; inside I/O callbacks setImmediate beats setTimeout.
  • Use pipeline for streams, { recursive: true } for folders, and AbortSignal for timeouts and cancellation.
  • fetch resolves for 4xx and 5xx; check response.ok.
  • Use 127.0.0.1 and port 0 for local servers in examples and tests.
  • Test errors by code, set process.exitCode, and keep the original error as cause when you wrap one.

Next: Practice Problems: Core Node