Lesson 1 of 8 · 11 min · The Node.js runtime
Node.js runtime: event loop and non-blocking I/O
What you will learn
- What Node.js is and what it is good at
- How the event loop and non-blocking I/O let one thread serve many users
- The difference between blocking and non-blocking calls
- Use the promise-based APIs (
fs/promises,fetch, timers) - What to avoid in request handlers, and the built-in tools you get
In simple words
Node.js lets you run JavaScript outside the browser, usually to build servers. A restaurant with one very fast waiter works as a picture: the waiter takes your order, passes it to the kitchen and, instead of standing there waiting, takes the next table's order. When the kitchen rings the bell, the waiter serves the dish. Node.js is that waiter: one thread that never waits for slow things like files and databases, which is why one process can handle thousands of connections.
Words to know
- Node.js: a JavaScript runtime built on Chrome's V8 engine, for running JavaScript on servers and in tools.
- I/O: input and output, such as reading files, network calls and database queries.
- Non-blocking: starting an operation and continuing with other work until it finishes.
- libuv: the library that gives Node.js its event loop and thread pool.
What Node.js is
Node.js combines the V8 JavaScript engine with a library of system APIs (files, network, processes, crypto) and the event loop from libuv. It is used for web servers and APIs (Express, Fastify, NestJS), command-line tools, build tools (Vite, webpack, ESLint, Prettier all run on Node.js), real-time apps (WebSockets) and scripts. It is a strong fit for I/O-heavy work (many connections, waiting on databases and other services) and a poor fit for CPU-heavy work on the main thread (video encoding, big number crunching), unless you use worker threads or separate services.
Use a current LTS version (22 or 24 at the time of writing; even-numbered releases become LTS). Check with node --version; manage versions with nvm, fnm or Volta.
node --version
node server.js
node --watch server.js # restart on file changes (built in)
node --env-file=.env server.js # load environment variables from a file (built in)
node --test # built-in test runner
The event loop in a server
Your JavaScript runs on one thread. When your code asks for something slow, Node.js hands it to the system (the operating system's asynchronous network calls, or a thread pool of worker threads for file system, DNS and crypto), then moves on. When the operation finishes, a callback or promise continuation is queued and the event loop runs it when the main thread is free (the JavaScript event loop lesson described the browser version; Node.js has the same idea with different phases).
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
const server = createServer(async (req, res) => {
const text = await readFile("./data.json", "utf8"); // does not block other requests
res.writeHead(200, { "Content-Type": "application/json" });
res.end(text);
});
server.listen(3000, () => console.log("listening on http://localhost:3000"));
While this handler is awaiting the file, the event loop serves other incoming requests. A thousand slow requests waiting on databases cost memory, not threads.
Blocking versus non-blocking
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
// BLOCKING: the whole process waits; no other request is served meanwhile
const a = readFileSync("big.csv", "utf8");
// NON-BLOCKING: other work continues while the file is read
const b = await readFile("big.csv", "utf8");
Rules of a healthy server:
- Never use synchronous APIs in request handlers (
readFileSync,execSync,crypto.pbkdf2Sync,spawnSync). They are fine at start-up (reading configuration once) and in scripts. - Do not run long CPU loops on the main thread (large
JSON.parse, sorting millions of rows, image processing, regular expressions with catastrophic backtracking). While one user's work runs, every other request waits and the server looks frozen. Move heavy work to worker threads (a later lesson) or a queue and separate worker service. - Do not block with
awaitin a loop over independent work; start it together withPromise.all. - Limit concurrency when calling a database or API (a pool, or
p-limit) so you do not open ten thousand connections at once.
Because there is one thread, a bug that throws and is not caught can crash the process, taking all users with it. Handle errors, and run Node.js under a process manager or container platform (Docker restart policy, systemd, PM2, Kubernetes) that restarts it.
Promises and async APIs
Modern Node.js APIs return promises. Prefer them over the older callback style:
import { readFile, writeFile, readdir, stat } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";
const files = await readdir("./uploads");
const info = await stat("./uploads/cv.pdf");
await writeFile("./out.json", JSON.stringify({ ok: true }));
await sleep(1000);
const response = await fetch("https://api.example.com/orders"); // built in since Node 18
const orders = await response.json();
node:prefix for built-in modules (node:fs,node:path,node:http,node:crypto,node:os) avoids confusion with npm packages.util.promisifyconverts old callback functions:const run = promisify(execFile);.- Run independent tasks together:
await Promise.all([readFile(a), readFile(b)]). - Always handle rejections; an unhandled rejection terminates the process in modern Node.js. Add a last-resort handler for logging and a graceful shutdown:
process.on("unhandledRejection", (reason) => { console.error("Unhandled rejection", reason); process.exit(1); });
process.on("uncaughtException", (error) => { console.error("Uncaught exception", error); process.exit(1); });
After an uncaught exception the process state is unreliable, so log and exit, and let the platform restart it.
Timers and scheduling
setTimeout(() => console.log("later"), 100);
setInterval(tick, 1000); // clearInterval later; unref() lets the process exit if only the timer remains
setImmediate(() => console.log("after the current I/O phase"));
process.nextTick(() => console.log("before other async work, use sparingly"));
queueMicrotask(() => console.log("a promise-like microtask"));
Heavy use of process.nextTick or endless microtask loops can starve the event loop and delay I/O; avoid recursive scheduling without yielding.
Environment, configuration and process basics
const port = Number(process.env.PORT ?? 3000);
const isProd = process.env.NODE_ENV === "production";
console.log(process.argv.slice(2)); // command-line arguments
console.log(process.cwd(), import.meta.dirname); // working directory and this file's directory (Node 20.11+)
- Keep configuration in environment variables (12-factor style), loaded with
--env-fileor a platform; never commit secrets, and keep a.env.example. - Graceful shutdown: on
SIGTERM(sent by Docker and Kubernetes), stop accepting connections, finish in-flight requests, close the database pool and exit:
process.on("SIGTERM", () => {
server.close(() => process.exit(0));
setTimeout(() => process.exit(1), 10_000).unref(); // force exit if it takes too long
});
- Use structured logging (
pino) with levels and request ids, not scatteredconsole.log. - Check memory and event loop lag in production (
process.memoryUsage(),perf_hooks.monitorEventLoopDelay()); high lag means something blocks the loop.
Scaling a Node.js service
One Node.js process uses one CPU core for JavaScript. To use more cores or more machines:
- Run several processes behind a load balancer (containers, the
clustermodule, PM2 cluster mode) and keep the application stateless: sessions in Redis, uploads in object storage, no in-memory caches that must be shared. - Use worker threads for CPU tasks within one process.
- Put slow jobs (email, report generation, video) on a queue (BullMQ with Redis, SQS) processed by worker processes.
- Use caching and CDNs for repeated reads.
Useful built-ins to know
node:testandnode --testfor tests (withnode:assert),--watch,--experimental-test-coverage.fetch,AbortController,URL,URLSearchParams,structuredClone,crypto.randomUUID(): web-standard APIs available globally.node:util(parseArgsfor CLI flags,styleText),node:readline,node:child_process,node:os,node:path.- Permission model (
--permission) can restrict file and network access in newer versions. - Recent versions can run TypeScript files that use only erasable syntax by stripping types (
node file.ts), but you still type-check withtsc.
Common mistakes
- Synchronous calls in request handlers.
- CPU-heavy work on the main thread.
- Unhandled promise rejections (process crashes).
- Keeping per-user state in memory (breaks when you run several processes).
- No graceful shutdown and no restart policy.
- Unbounded concurrency to databases and APIs.
- Using
console.logfor production logging and logging secrets.
Try it yourself
- Write an HTTP server with
node:httpthat returns JSON, and run it withnode --watch. - Add a route that does
readFileSyncof a large file, call it from two terminals at once and watch the second wait; then switch toreadFile. - Write a route with a 2-second CPU loop and show that
/healthstops responding during it. - Read three files with
Promise.alland compare the time with reading one after another. - Add
SIGTERMhandling that closes the server gracefully.
Check yourself
Why can a single Node.js thread handle thousands of connections?
Slow operations such as network and file I/O are handed to the operating system or a thread pool, and the main thread keeps running other callbacks, so waiting costs no thread.
What is wrong with fs.readFileSync inside a request handler?
It blocks the event loop, so no other request is served until it finishes.
What happens to an unhandled promise rejection in modern Node.js?
It raises an error that terminates the process by default, so rejections must be handled.
How do you use several CPU cores with Node.js?
Run multiple processes (cluster, containers behind a load balancer) and use worker threads for CPU-heavy tasks, keeping the app stateless.
Interview questions
Is Node.js single-threaded?
Your JavaScript runs on one main thread with an event loop, but Node.js uses a libuv thread pool and the operating system for I/O, and you can add worker threads and processes.
When is Node.js a poor choice?
For CPU-bound tasks on the main thread, because they block the event loop; use worker threads, separate services or a language suited to heavy computation.
What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?
process.nextTick runs before other asynchronous work in the current operation, setImmediate runs in the check phase after the poll phase, and setTimeout(fn, 0) runs in the timers phase after at least the minimum delay.
Summary
- Node.js runs JavaScript on V8 with an event loop and non-blocking I/O, ideal for many concurrent connections.
- Never block the loop: no sync APIs or long CPU work in handlers; use promises,
Promise.alland bounded concurrency. - Handle errors, log and exit on uncaught exceptions, shut down gracefully and run under a restarting supervisor.
- Scale with multiple stateless processes, worker threads and queues.
Going deeper
- Node.js: Introduction: what Node.js is.
- Node.js: The event loop, timers and nextTick: the phases explained.
- Node.js: Don't block the event loop: official guidance.
- Node.js: File system API: synchronous, callback and promise APIs.
See how much of this you can explain
A free mock interview asks you new questions on Node.js and Express backends for Full Stack Developer and scores every answer, with what to fix.