2026-11-11·by Sijie Wang#fundamentals

nodejs

Node.js is a JavaScript runtime built on V8 and libuv: one main thread runs JavaScript, an event loop decides when each callback runs, libuv waits on the operating system and does the blocking work, and V8 turns JavaScript into machine code.

Node.js is a JavaScript runtime built on V8 and libuv: one main thread runs JavaScript, an event loop decides when each callback runs, libuv waits on the operating system and does the blocking work, and V8 turns JavaScript into machine code.

1. The event loop

What it is. The event loop is a loop the main thread runs forever. Each turn walks six phases in a fixed order and runs the callbacks that are due in each phase.

  • timers. Expired timers: setTimeout and setInterval callbacks whose time has come.
  • pending callbacks. I/O callbacks deferred from the previous turn.
  • idle, prepare. Internal bookkeeping.
  • poll. Waits for I/O events and runs I/O callbacks. How long it waits is decided by the nearest timer.
  • check. setImmediate callbacks.
  • close callbacks. Closing callbacks, for example socket close handlers.

Why the order is fixed but the result is not. The phases always run in the same order, but whether a timer is due when its phase comes around depends on timing. setTimeout(0) is really recorded as 1ms. Whether the timer is due at the first timers phase depends on how fast the loop starts after the synchronous code finishes.

Inside an I/O callback, setImmediate always wins. The callback runs in the poll phase, and the next phase is check, so the immediate callback runs before the next timers phase no matter what.

2. Microtasks

What they are. Microtasks are small jobs that run between the loop's steps. After each callback finishes, the loop drains the microtask queues before moving on to the next phase. process.nextTick runs before Promise callbacks.

The rule that follows. Microtasks run before the loop can move on, so a nextTick callback that keeps registering another nextTick starves the loop: no phase ever runs. Never recurse through nextTick.

3. libuv

What it is. libuv is the C library underneath Node that talks to the operating system. The main thread must never wait on anything slow, so libuv does the waiting and the blocking work for it.

Why two different mechanisms. Waiting and working are different problems, and the operating system offers different tools for them.

  • epoll waits on network file descriptors only. It waits for a readiness change on a descriptor. A file is always ready, so there is nothing to wait for; a DNS lookup (getaddrinfo) is a blocking function call with no descriptor at all. Neither can go through epoll.
  • The thread pool does the blocking work. Four threads by default, shared by file I/O, DNS, encryption, and compression. Ten files means four running and six queued, first-in first-out. UV_THREADPOOL_SIZE must be set before the process starts.

The loop's cycle. Wait for work, do the work, hand the results back, wait again.

When the main thread is busy, nothing is lost. Events are data, not signals. An expired timer is a timestamp sitting in a min-heap; a finished file read is one more entry in the completion queue; a new connection is one more entry in the backlog. Registering an event does not need the main thread; only running its callback does. New requests are lost only when the backlog is full (the kernel drops them) or the client times out.

Heavy work has two exits. Split it into pieces and yield between them with setImmediate, or move it off the main thread with worker_threads.

4. V8

What it is. V8 is the JavaScript engine: it turns source code into machine code and runs it. It only executes; the event loop decides when.

The pipeline, motivation first. Interpretation starts fast but runs slow; compilation starts slow but runs fast. V8 does both, in order: Parser turns source into an AST; Ignition interprets the AST as bytecode and starts running at once; type feedback (hidden classes: objects with the same shape share one layout) tells the compiler what the code actually does; TurboFan compiles hot code to machine code; when an assumption breaks, the code deoptimizes and falls back to bytecode.

Garbage collection. The young generation uses Scavenge (most objects die young, so copy the survivors and drop the rest); the old generation uses mark-and-sweep.

One engine per thread. Each worker_threads worker has its own V8 instance; they share nothing by default.

5. Stream and Cluster

Stream: what it is. A stream moves data in chunks instead of all at once. It exists so a large file or a slow network does not have to fit in memory before anything can happen.

Backpressure: the mechanism. The writer says how much it can take. write returns false when the buffer is full: stop writing, wait for drain, then continue. pipe handles this automatically. File streams buffer 64KB by default. The rule that follows: never read a big file whole with readFile; use a stream.

Cluster: what it is. One Node process uses one CPU core. Cluster forks several worker processes that share one port; the main process distributes connections round-robin, and workers talk to each other through IPC.

How the three concurrency tools differ. The thread pool is for blocking work inside one process. worker_threads are threads inside one process, for CPU-heavy work, each with its own V8 instance. Cluster is separate processes, for using multiple CPU cores, each with its own V8 instance and memory.

6. Buffer, modules, errors

Buffer: what it is. JavaScript has no binary type, so Buffer is Node's binary container: file reads, network transfers, images, audio, encryption all move as Buffers.

Where it lives. Off-heap, outside the V8 heap: binary data does not squeeze the garbage collector, and it is not limited by the heap size. Small Buffers under 4KB share one 8KB pool, so small allocations do not each ask the system for memory; the price is that a small slice keeps the whole pool alive. Buffer.alloc zeroes the memory (safe, slower); Buffer.allocUnsafe does not zero it (fast, may read old data). slice is a view, not a copy: changing the slice changes the original.

Modules: what they are. require and module.exports split code into files that reference each other.

The mechanism. Requiring a file wraps it in a function (exports, require, module, __filename, __dirname), runs it once, hangs the result on module.exports, and caches it in require.cache. A second require of the same file reads the cache and does not run the file again, so a module's exports are naturally a singleton.

Circular dependencies. When A requires B and B requires A, B's require of A runs while A is only half executed, so B gets A's incomplete exports. The fix: put exports at the top of the file, do not use the other module at the top level, and require lazily inside a function.

CommonJS vs ESM. CommonJS loads synchronously at runtime; ESM loads asynchronously with static analysis, and import is a read-only live binding: if the other side changes the value, the change is visible. .mjs is ESM, .cjs is CommonJS, .js follows the nearest package.json type field.

Errors: two kinds. Synchronous errors are caught by try/catch. Asynchronous errors arrive as the first callback argument (err), a Promise rejection, or an EventEmitter error event. An error event with no listener crashes the process outright.

  • uncaughtException. Where a synchronous error lands when nobody catches it. The default is to print and exit. Listening keeps the process alive, but the state may already be corrupt: the correct move is to log, exit gracefully, and let the process manager restart it.
  • unhandledRejection. A Promise that rejected with nobody catching it. Since Node 15 it exits the process by default, the same as an uncaught exception.

The rules that follow. Check err first in every callback; every Promise gets a catch; the top level listens for uncaughtException to do cleanup and restart. try/catch cannot catch an error thrown inside an asynchronous callback, so do not write it that way.

7. Applied: rules and diagnosis

Writing code. Do not block the main thread; do not let microtasks or nextTick starve the loop; Node is for I/O-heavy work, not CPU-heavy work; the thread pool fills up, so tune UV_THREADPOOL_SIZE when file, DNS, or crypto work queues up.

Diagnosing in production. The number to watch is event loop lag: perf_hooks.monitorEventLoopDelay measures how late the loop runs behind schedule. When lag grows, look for the usual suspects: a big synchronous loop, a big JSON.parse, a regex that backtracks.

about this entry

One of sijie's wiki entries. The AI on this site is grounded in the same corpus and answers in sijie's voice, with citations back to entries like this one — answering costs sijie money, so it waits behind a code: enter an access code →

nodejs — Sijie Wang