Skip to content

Lesson 18 of 50JavaScript in depth

JavaScript on the Server: Node.js

What Node adds to JavaScript: built-in modules, process and env, ESM vs CommonJS, running TypeScript directly, streams, node:test and release lines.

15 min read0/4 questions

Your first ticket on a new team is rarely a React component. More often it is a script: read a 2 GB export from the payments system, count the failed rows, and post a summary to Slack every night. Or a build step that fails only on the CI server. Or an API that slowly runs out of memory. All of these run on Node.js, the program that runs JavaScript outside the browser. The language is the same one you already know, but the world around it is different: there is no window and no DOM, and instead you get files, processes, environment variables and the network. This lesson covers what a working engineer needs to know about that world, so a Node script or service does not feel like a black box.

What Node actually is

Node is three things glued together:

  • V8, the same JavaScript engine Chrome uses. It parses, compiles and runs your code. Your language knowledge transfers directly.
  • libuv, a C library that provides the event loop and non-blocking I/O. When you read a file or open a socket, libuv hands the work to the operating system (or to a small thread pool for things the OS cannot do asynchronously, like most file system calls and crypto.pbkdf2) and calls you back when it is done. You met its phases in Node's loop, briefly, in the event loop lesson.
  • Built-in modules written in JavaScript and C++: fs, path, http, crypto, child_process and more. They are the server's equivalent of browser APIs.
What runs when you type node app.js
  1. Your code and npm packagesapp.js, express, zod
  2. Node built-in modulesnode:fs, node:http, node:crypto
  3. V8runs the JavaScript, manages memory
  4. libuvevent loop, thread pool, async I/O
  5. Operating systemfiles, sockets, processes

Your code calls readFile("orders.csv"). To you it is just a function that returns a promise.

1/5

The consequence that matters at work: one JavaScript thread serves every request. I/O waits are free, because they happen elsewhere. CPU work is not. A synchronous loop that takes 200 ms to hash passwords or parse a huge JSON blob blocks every other user for those 200 ms. This is the single most common cause of "the API is randomly slow" in Node services.

Built-in modules worth knowing

Import built-ins with the node: prefix. It makes clear the module is built in, and no npm package can hijack the name.

ModuleUse it for
node:fs/promisesReading and writing files with await (readFile, writeFile, mkdir, readdir)
node:pathJoining paths safely across operating systems (path.join, path.resolve, path.extname)
node:urlfileURLToPath, and the same URL class the browser has
node:cryptorandomUUID(), hashing (createHash("sha256")), timingSafeEqual for comparing secrets
node:child_processRunning other programs (execFile, spawn)
node:worker_threadsReal extra threads for CPU-heavy work
node:streamProcessing data piece by piece instead of all at once
node:utilparseArgs for command-line flags, styleText for coloured output

Some globals differ from the browser. Node has process, Buffer and global (use globalThis, which works everywhere). It has no window, document or localStorage. It does share many web APIs now: fetch, URL, AbortController, structuredClone, TextEncoder, crypto.randomUUID and web streams are all global in current Node, so code using them often runs in both places.

The process: arguments, environment and exit codes

Every Node program runs as an operating system process, and the global process object is your view of it.

process.argv holds the command line. The first two entries are the path to node and the path to your script, so your arguments start at index 2. For anything beyond one or two arguments, use the built-in parser instead of slicing strings by hand:

scripts/report.ts
import { parseArgs } from "node:util";
 
const { values, positionals } = parseArgs({
  options: {
    since: { type: "string" },
    verbose: { type: "boolean", short: "v" },
  },
  allowPositionals: true,
});
 
// node scripts/report.ts orders.csv --since 2026-10-01 -v
console.log(positionals[0], values.since, values.verbose); // orders.csv 2026-10-01 true

process.env holds environment variables, always as strings (or undefined). process.env.PORT is "3000", not 3000, and process.env.DEBUG === "false" is a truthy string. Parse and validate them once at startup, ideally with a schema, and fail fast with a clear message if one is missing. Node reads .env files itself now, so you no longer need the dotenv package for that:

node --env-file=.env server.jsnode --env-file-if-exists=.env.local server.js   # no error if the file is missing

Exit codes tell whoever started your process whether it worked. 0 means success; anything else is failure. CI systems, shell scripts, Docker and Kubernetes all read this number. A script that catches an error, logs it and then exits with 0 will show a green tick on a broken build. Uncaught exceptions and unhandled promise rejections exit with code 1.

There are two ways to set the code, and the difference bites people:

  • process.exitCode = 1 sets the code and lets Node finish naturally: pending timers, open writes and log flushes complete first. Prefer this.
  • process.exit(1) stops immediately. Anything still queued is dropped, including log lines that had not been flushed yet.
Predict the outputJavaScript

What does this print?

process.on("exit", (code) => console.log("exit", code));
setTimeout(() => console.log("timer"), 0);
process.exit(2);
console.log("end of script");
Need a nudge? Hints walk you through it.

Signals and graceful shutdown

When Kubernetes, Docker or a deploy platform stops your service, it sends SIGTERM and waits a short grace period before killing the process outright. Ctrl+C in a terminal sends SIGINT. A production server should catch these, stop accepting new requests, let in-flight requests finish, close database connections, and then exit:

src/server.ts
const server = app.listen(3000);
 
process.on("SIGTERM", () => {
  console.log("SIGTERM: draining connections");
  server.close(async () => {
    await db.end();
    process.exitCode = 0;
  });
  // Safety net: if draining hangs, give up before the platform kills us
  setTimeout(() => process.exit(1), 10_000).unref();
});

Without this, every deploy cuts off users mid-request. unref() tells Node not to stay alive just for that timer.

ESM and CommonJS in Node

Node has two module systems, and you will work with both. CommonJS (CJS) is Node's original system: require() and module.exports. ES modules (ESM) are the standard import/export you saw in Modules and npm. Node decides which one a file uses like this:

  1. .mjs is always ESM. .cjs is always CommonJS.
  2. For .js, Node looks at the nearest package.json. "type": "module" means ESM; no type field (or "commonjs") means CJS.
  3. If there is no type field and the file contains ESM syntax, current Node detects it and runs it as ESM anyway. Do not rely on that: set "type" explicitly.

The differences you will trip over:

  • ESM has no require, __dirname or __filename. Use import.meta.dirname and import.meta.filename instead (built in since Node 20.11 and 21.2).
  • ESM relative imports need the file extension: import { x } from "./util.js", not "./util".
  • ESM allows top-level await. CJS does not.

For years the painful rule was that CJS could not require() an ES module, which forced libraries to ship two copies. That is no longer true: require(esm) works without a flag in Node 22.12+ and 20.19+, as long as the ES module does not use top-level await. Because of this, many popular packages now ship ESM only. New code should be ESM with "type": "module".

Quick check
A file scripts/seed.js uses import and __dirname. package.json has "type": "module". What happens when you run it?
Need a nudge? A hint rules out a wrong answer.

Running TypeScript directly

Current Node runs .ts files with no build step. Type stripping is on by default in Node 22.18+ and in 23.6+ (so every current release line has it): Node replaces each type annotation with blank space and runs what is left. node scripts/report.ts just works.

It does not type-check anything. A file full of type errors runs happily. You still run tsc --noEmit in CI and rely on your editor, exactly as the TypeScript toolchain lesson explains.

It also only handles erasable syntax: types that can be deleted without changing what the code does. These fail with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX:

  • enum (it generates a runtime object). Use a const object with as const and a union type.
  • namespace with runtime code.
  • Constructor parameter properties like constructor(private db: Db).

Two more rules catch people:

  • Write the real extension in imports: import { total } from "./price.ts". Node does not guess.
  • Mark type-only imports: import { type User, loadUser } from "./users.ts". Without type, Node looks for a runtime export called User, finds none and throws a SyntaxError.

Set "erasableSyntaxOnly": true, "verbatimModuleSyntax": true and "allowImportingTsExtensions": true (with noEmit) in tsconfig.json, and your editor flags all of this before Node does. Type stripping also skips files inside node_modules, so packages must still publish JavaScript.

Bun and Deno: the alternatives

Bun and Deno are other JavaScript runtimes. Both run TypeScript directly, include a test runner, formatter and package tooling, and aim for Node compatibility (they implement most node: modules and read package.json). Bun is built on JavaScriptCore (Safari's engine) and is known for very fast installs and startup. Deno, from Node's original creator, has a permission system: a script cannot read files or use the network unless you grant it.

Teams pick Bun mostly for speed in scripts, tests and installs, and Deno for its security model and built-in tooling. Benchmarks published by runtime vendors measure what flatters them; your workload is what counts. Most companies still run Node in production because it is the default every cloud, library and monitoring tool supports first. Knowing Node well transfers to both.

Streams and backpressure

Your nightly script has to count failed rows in a 2 GB log file. await readFile("access.log", "utf8") loads all 2 GB into memory as one string, which is slow and can crash the process (V8 also caps string length well below that). The fix is a stream: read the file in chunks of about 64 KB, process each one, and let it go.

There is a trap. Chunks are cut by size, not by line, so a line can be split across two chunks. Run this simulation:

JavaScript
// A file arrives as chunks. Chunk edges ignore line breaks.const chunks = ["GET /a 200\nGET /b 5", "00\nPOST /c 2", "01\nGET /d 404\n"]; // Naive: split each chunk on its ownconst naive = chunks.flatMap((c) => c.split("\n")).filter(Boolean);console.log("naive:", naive); // Correct: keep the unfinished tail and glue it to the next chunkfunction* lines(chunks) { let tail = ""; for (const chunk of chunks) { const parts = (tail + chunk).split("\n"); tail = parts.pop(); // last piece may be half a line yield* parts; } if (tail) yield tail;}console.log("correct:", [...lines(chunks)]); const statuses = {};for (const line of lines(chunks)) { const status = line.split(" ").at(-1); statuses[status] = (statuses[status] ?? 0) + 1;}console.log(statuses);
Output
Press Run (⌘ Enter) to see what happens.

The naive version invents statuses 5 and 2. In Node you do not write the tail logic yourself; node:readline does it, and streams are async iterable, so the real script is short:

scripts/count-statuses.ts
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
 
const lines = createInterface({ input: createReadStream("access.log"), crlfDelay: Infinity });
const counts: Record<string, number> = {};
 
for await (const line of lines) {
  const status = line.split(" ").at(-1) ?? "?";
  counts[status] = (counts[status] ?? 0) + 1;
}
console.log(counts); // memory stays flat whether the file is 7 MB or 7 GB

Backpressure

The other half of streaming is backpressure: what happens when the source produces data faster than the destination can take it. Reading a local disk is fast; uploading to S3 or writing to a slow socket is not. A writable stream has a buffer limit (its highWaterMark). When write() returns false, the buffer is full and the producer should pause until the drain event. Code that ignores the return value keeps piling data into memory:

JavaScript
// Backpressure, simulated. A fast reader feeds a slow writer.function run({ respectBackpressure }) { const highWaterMark = 4; // the writer's buffer limit, in chunks let buffered = 0; let peak = 0; let paused = 0; for (let tick = 1; tick <= 20; tick++) { // the reader produces 3 chunks per tick for (let i = 0; i < 3; i++) { if (respectBackpressure && buffered >= highWaterMark) { paused++; // write() returned false: wait for "drain" continue; } buffered++; } peak = Math.max(peak, buffered); buffered = Math.max(0, buffered - 1); // the writer flushes 1 chunk per tick } return { peakBuffered: peak, pausedWrites: paused };}console.log("ignore:", run({ respectBackpressure: false }));console.log("respect:", run({ respectBackpressure: true }));
Output
Press Run (⌘ Enter) to see what happens.

Ignoring backpressure, the buffer grows without limit (41 chunks after 20 ticks, and it keeps going). Respecting it, memory never passes the limit. You rarely handle drain by hand. pipeline() from node:stream/promises connects streams, handles backpressure between every pair, and, just as important, destroys all of them and rejects if any one fails:

import { createReadStream, createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { createGzip } from "node:zlib";
 
await pipeline(createReadStream("access.log"), createGzip(), createWriteStream("access.log.gz"));

The old a.pipe(b).pipe(c) style does not forward errors, so a failure in the middle leaves file handles open and the promise you were waiting on never settles. Use pipeline.

When you need more than one thread

For CPU-heavy work (image resizing, big parses, hashing many passwords), move it off the main thread with worker_threads, or a pool library built on it, so requests keep flowing. To run another program, use child_process. To use every CPU core for a web server, platforms usually run several Node processes behind a load balancer rather than one process with workers.

node:test, watch mode, and when Vitest wins

Node ships a test runner. node --test finds files like *.test.js and *.test.ts, and node:assert/strict gives you assertions. It also has mock.fn(), mock timers, describe and coverage.

src/price.test.ts
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { subtotal } from "./price.ts";
 
describe("subtotal", () => {
  test("adds price times quantity", () => {
    assert.equal(subtotal([{ cents: 250, qty: 2 }]), 500);
  });
});

node --watch server.ts restarts on file changes, replacing nodemon, and node --run build runs a package.json script faster than npm run. For a small library or a tool with zero dependencies, node:test is a fine choice. For an application, most teams choose Vitest: richer matchers, vi.mock for modules, snapshot testing, a far better watch mode, and it reuses your Vite config and path aliases. That is the next lesson in this unit.

Release lines: which Node to run

Node ships a new major version every six months. Even-numbered majors become LTS (long-term support) about six months after release and get around 30 months of fixes; odd-numbered majors live only a few months and are for trying new features. In production, run an Active LTS or Maintenance LTS line, never an odd release and never an end-of-life one.

As of late 2026, Node 24 is the main LTS line, Node 22 is in maintenance, and Node 26 is due to enter LTS at the end of October. Node 20 reached end of life in April 2026, so it gets no security fixes, and tutorials that say "use Node 18 or 20" are out of date. Check the release schedule at nodejs.org before you pick a version, and pin it in one place (.nvmrc, "engines" in package.json, and the Docker base image) so local, CI and production agree.

Put it in order5 steps

Your service gets SIGTERM during a deploy. Put a graceful shutdown in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each task to the Node tool you would reach for.

Choose an item, then its match on the other side.
Key terms
libuv
The C library under Node that provides the event loop, async I/O and a small thread pool.
exit code
The number a process returns when it ends. 0 means success; anything else tells CI or the platform it failed.
SIGTERM
The signal platforms send to ask a process to stop. Catch it to shut down gracefully.
type stripping
Node running .ts files by deleting type annotations. No type checking, and only erasable syntax.
require(esm)
Loading an ES module from CommonJS with require, unflagged in Node 22.12+ and 20.19+.
backpressure
A slow consumer signalling a fast producer to pause, so buffered data does not grow without limit.
LTS
Long-term support. Even-numbered Node majors that get security fixes for years. Run these in production.