Node.js tutorial
Run JavaScript outside the browser: scripts, files, servers and tools with Node.js.
Course contents
Node.js Foundations
- Introduction to Node.js — What Node.js is and why it was made, its history, V8, libuv and C++ bindings, Node.js versus browser JavaScript, Deno and Bun, LTS versus Current, installing Node.js and version managers, running scripts, the REPL, common CLI flags, and the global object, console and built-in globals.
- Modules in Node.js — What a module is, module scope, CommonJS with require and module.exports, the module wrapper, how Node.js finds modules, caching and circular imports, JSON files, ES modules with import and export, import.meta, dynamic import and top-level await, using CommonJS and ES modules together, and running TypeScript files.
- Packages and npm — What npm and the npm registry are, package.json fields, dependency types, installing and updating packages, semantic versioning and version ranges, package-lock.json and npm ci, npm scripts and node --run, npx and local binaries, how Vite and the Angular CLI use Node.js, npm audit, package entry points with exports and imports, and optional workspaces, publishing and other package managers.
Asynchronous Node.js
- Event Loop and Timers — How Node.js runs many jobs on one thread: blocking and non-blocking code, I/O-bound and CPU-bound work, the call stack, libuv and the thread pool, the event loop phases, timers, setImmediate, timers/promises, process.nextTick and the microtask queue, predicting output order, and how to avoid blocking the event loop.
- Events and Utilities — The observer pattern and EventEmitter: on, once, off, emit, prependListener, listener helpers, synchronous emit, arguments, the error event, captureRejections, listener limits, extending EventEmitter, events.once and events.on. Error-first callbacks, the util module (promisify, callbackify, inspect, format, types, isDeepStrictEqual, deprecate), cancelling work with AbortController and AbortSignal, and AsyncLocalStorage.
- Error Handling — Reading Node.js errors and stack traces, error.cause, system errors with code, errno, syscall and path, common error codes, Node.js ERR_ codes, operational versus programmer errors, thrown exceptions, rejected promises and error events, custom error classes, and process-level handlers: uncaughtException, unhandledRejection, the warning event and the fail-fast strategy.
System and Files
- Process, OS and CLI Tools — The process object (argv, env, platform, arch, version, pid, cwd, uptime and process events), environment files with --env-file and process.loadEnvFile, standard input, output and error, TTY detection and shell piping, exit codes, process.exit versus process.exitCode, the exit and beforeExit events, signals such as SIGINT and SIGTERM, the os module, and building command-line tools with a shebang, the bin field, util.parseArgs, help output, util.styleText and npm link.
- Path and File System — Building file paths with the path module (join, resolve, normalize, relative, basename, dirname, extname, parse, format, isAbsolute, sep and delimiter), Windows and POSIX paths, fileURLToPath and import.meta.dirname, the sync, callback and promise fs APIs, reading text, JSON and folders, writing and appending, file flags, safe writes, copying, renaming and deleting, mkdir and mkdtemp, checking existence without race conditions, stat and permissions, symlinks, low-level file handles and watching files.
- Buffers, Streams and Compression — Buffers and raw bytes (alloc, allocUnsafe, from, encodings, concat, subarray, compare, equals, indexOf, typed arrays, string_decoder), why streams save memory, readable streams (flowing and paused modes, events, async iteration, highWaterMark, Readable.from, createReadStream), writable streams and backpressure, duplex and transform streams, object mode, composing streams with pipe and pipeline, the readline module, gzip, deflate and Brotli compression with zlib, and web streams.
Networking and Parallelism
- HTTP and Networking — Sockets and streams, how net, http and tls relate, building an HTTP server with http.createServer, IncomingMessage and ServerResponse, reading the method, URL, headers and body, sending JSON, manual routing, serving files with streams, listen options and server events, HTTP clients with http.request and fetch, keep-alive and agents, server timeouts, why frameworks like Express exist, TCP with net, HTTPS and HTTP/2, UDP, DNS and TLS, and local sockets.
- Child Processes, Worker Threads and Clustering — When to use parallelism, recognising CPU-bound work, child processes with exec, execFile, spawn and fork, options, streaming output, IPC, killing and detaching processes and handling their errors, worker threads with workerData, parentPort, message passing, structured clone, transferable objects, errors, termination and worker pools, SharedArrayBuffer and Atomics, MessageChannel and resource limits, the cluster module, and choosing between child processes, worker threads and cluster.
Quality and Production
- Testing with the Built-in Test Runner — Why tests matter, unit and integration tests, Arrange-Act-Assert, node:test with test, describe and it, running tests with node --test, test file discovery, subtests, async tests, skip, todo and only, timeouts and reporters, node:assert strict mode, hooks, mocking functions, methods and timers, testing file-system code, EventEmitters, streams, HTTP servers and CLI tools, test coverage, watch mode, and how node:test compares with Vitest and Jest.
- Debugging and Profiling — The debugger statement, source maps, NODE_DEBUG and util.debuglog, the inspector with --inspect and --inspect-brk, debugging in Chrome DevTools and VS Code, breakpoints and watch expressions, remote debugging safety, measuring time with perf_hooks, performance.now, process.hrtime.bigint, marks, measures and PerformanceObserver, event loop delay and utilization, CPU profiling with process.cpuUsage, --cpu-prof, --prof and flame graphs, memory with process.memoryUsage, heap and RSS, garbage collection, --max-old-space-size, heap snapshots and common leaks, and diagnostic reports.
- Cryptography and Security — What node:crypto covers and how it compares with Web Crypto, hashing with createHash and hashing files with streams, hashing versus encryption, weak algorithms, HMAC, secure random values with randomBytes, randomInt and randomUUID, password hashing with salts, scrypt, pbkdf2, cost settings and timingSafeEqual, AES-256-GCM encryption with IVs and auth tags, key derivation, asymmetric keys and signatures, secure coding against path traversal, command injection, prototype pollution, ReDoS, eval and vm, decompression bombs and supply chain attacks, and the Node.js permission model.
- Production Readiness — What NODE_ENV changes in Node.js and libraries, validating configuration at start-up, process managers and restart strategies, one process per container, running as PID 1, health check endpoints, graceful shutdown with signals, server.close and closeIdleConnections, finishing in-flight work and closing resources and workers, shutdown timeouts, --max-http-header-size and the compile cache, structured JSON logging and log levels, diagnostics_channel, safe Node.js upgrades with a CI version matrix and deprecation flags, single executable applications and bundling, and a pre-production checklist.
Project and Reference
- Capstone: Build a Report Card Service — A complete Node.js project in five steps: a command-line tool with parseArgs and an env file, streaming a marks file with readline and saving results safely, an EventEmitter-based report builder with custom errors, an HTTP API with health checks and graceful shutdown, and tests with node:test, followed by three extension exercises.
- Node.js Cheat Sheet — A one-page Node.js reference: core modules, CommonJS and ES module patterns, event loop order, process, fs and path, EventEmitter, streams and buffers, HTTP and networking, child processes and workers, node:test, crypto, CLI flags, package.json fields and npm commands, plus common error codes, error messages with fixes, and a glossary for beginners.