Tutorials Logic, IN info@tutorialslogic.com

Node.js Cheat Sheet: Runtime, Modules, Async I/O, HTTP, Testing, and Production

Node.js 24 LTS Quick Reference

Use this as a retrieval reference after completing the lessons. Each command or pattern points back to an engineering boundary; it is not a substitute for understanding ownership, limits, and failure behavior.

Project and Runtime Commands

Use node --version and npm --version to verify the toolchain, npm init -y to create package metadata, npm install for dependencies, npm install -D for development tools, npm ci for lockfile-exact automation, npm run name for scripts, node --test for tests, and node --env-file=.env app.mjs for stable built-in dotenv loading.

Declare type module for ES module .js files or use .mjs explicitly. Use .cjs for CommonJS where required. Commit package-lock.json, declare the supported Node engine, and use an LTS runtime in production.

Need Command
Run file node app.mjs
Run tests node --test
Inspect before start node --inspect-brk app.mjs
Exact install npm ci
Load environment node --env-file=.env app.mjs

Module and Location Patterns

Import built-ins with the node: prefix, local ES modules with explicit file extensions, JSON according to current module rules, and packages by their exports. Use import.meta.url plus fileURLToPath or new URL for module-relative files; use process.cwd only when the working directory is the intended input.

CommonJS exports through module.exports and loads with require. Do not mix default and named interop by guesswork. Package type, extension, and exports determine interpretation and public entry points.

Core ES Module Imports

Core ES Module Imports
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
const config = JSON.parse(await readFile(path.join(dirname, 'config.json'), 'utf8'));

The file path is stable regardless of the process working directory.

Async and Scheduling Reference

Await dependent work in order. Start independent bounded work together and use Promise.all when all results are required, allSettled when every outcome matters, any for first fulfillment, and race only when first settlement is truly the contract. Pass AbortSignal through supported APIs.

Synchronous code runs first, process.nextTick uses the Node-specific next-tick queue, promise reactions and queueMicrotask use microtasks, timers become eligible after a threshold, I/O callbacks run in their phases, and setImmediate runs in check. Avoid recursive microtasks and synchronous server APIs.

Buffer and Stream Reference

Create bytes with Buffer.from and initialized storage with Buffer.alloc. Convert with toString only when the encoding is known. Remember that subarray shares memory and that base64 is not encryption.

Use pipeline from node:stream/promises for owned transfers. Respect write returning false, preserve incomplete records across chunks, set input limits, and propagate abort. Readable, writable, duplex, and transform describe direction and behavior.

Promise Pipeline Pattern

Promise Pipeline Pattern
import { pipeline } from 'node:stream/promises';
await pipeline(source, transform, destination, { signal });

One awaited operation owns backpressure, errors, cancellation, and completion across the stages.

Files, Paths, and URLs

Prefer node:fs/promises for bounded file operations and streams for large data. Build paths with path.join or resolve, validate that untrusted candidates remain within an allowed root, and use atomic temporary-write then rename patterns where required.

Parse URLs with new URL and query parameters with URLSearchParams. The node:querystring module remains useful for compatibility with its specific escaping behavior, but URLSearchParams is the normal web-facing choice.

HTTP Server Checklist

Parse method and URL, bound headers and body bytes, validate content type and JSON shape, authenticate, authorize, apply domain work, then return deliberate status, headers, and body. Handle client abort, request timeout, partial response, and dependency cancellation.

Use 201 for creation, 204 for success without a body, 400 for malformed syntax, 401 for missing or invalid authentication, 403 for denied identity, 404 for absent resource, 409 for conflict, 413 for oversized body, 422 for domain-invalid input, 429 for rate limit, and safe 500 or 503 responses for server failures.

Process, Error, and Test Reference

Validate process.env at startup; values are strings. Use stdout for output, stderr for diagnostics, meaningful exit codes, SIGTERM for graceful shutdown, and a supervisor for restart. Treat uncaught exceptions and unhandled rejections as fatal boundaries.

Use node:test with node:assert/strict. Await async assertions, isolate ports and files, restore mocks, test real database contracts, and cover malformed input, cancellation, concurrency, startup, and shutdown. Preserve Error cause and map only known errors to public outcomes.

Security and Production Checklist

Validate and authorize, parameterize SQL, avoid shell interpolation, constrain paths, limit resources, protect secrets, install reproducibly, review dependencies, run least privilege, and consider the stable Node permission model as defense in depth.

Measure latency percentiles, errors, event-loop delay, CPU, RSS, heap, external memory, dependency time, queue pressure, and restarts. Deploy one immutable artifact with readiness, liveness, graceful shutdown, backward-compatible migrations, release telemetry, and a practiced rollback.

Before you move on

Retrieval Practice Check

4 checks
  • I can locate each command in its owning lesson.
  • I know the failure and resource boundary behind each snippet.
  • I use supported LTS documentation before adopting a version-sensitive API.
  • I can rebuild the capstone without relying on this page alone.

Node JS Questions Learners Ask

It targets stable APIs in Node.js 24 LTS as of July 2026 and labels choices that require version or deployment review.

Usually use URL and URLSearchParams. Keep node:querystring for compatibility when its exact parse or escape behavior is required.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.