All academies

Node.js Runtime

V8, libuv, bindings — how your JavaScript actually runs.

15 minLevel 6 of 20

The pieces of the runtime

Node.js is not one monolithic program — it is several components glued together:

  • V8 — Google's JavaScript engine. It parses your code, compiles it to machine code, and executes it. V8 knows nothing about files or networks.
  • libuv — a C library providing the event loop and asynchronous I/O: file operations, TCP sockets, DNS, timers, and a small thread pool for work the OS can't do asynchronously.
  • Node core APIs — the JavaScript standard library (fs, http, crypto...) you actually call.
  • Bindings — C++ glue connecting the JavaScript APIs to libuv and other native libraries.

When you call fs.readFile, the request travels: your JS → Node's fs module → C++ bindings → libuv → the operating system — and the result travels back up as a callback.

Evidence of the layers
// V8 executes this JavaScript...
const data = [3, 1, 2].sort();
console.log("V8 sorted:", data);

// ...while process exposes runtime internals:
console.log("Node version:", process.version);
console.log("Memory (heap used):",
  Math.round(process.memoryUsage().heapUsed / 1024) + " KB");

V8: compiling JavaScript on the fly

V8 uses just-in-time (JIT) compilation. Your source code is first turned into bytecode by an interpreter (Ignition), and functions that run frequently — *hot* functions — get recompiled into optimized machine code (by TurboFan). If assumptions behind an optimization break (say, a function suddenly receives strings instead of numbers), V8 *de-optimizes* and falls back to bytecode.

V8 also owns memory management: objects live on the heap and a garbage collector reclaims objects nothing references anymore. You never free memory manually in JavaScript.

Watching the heap
function mb(bytes) { return (bytes / 1024 / 1024).toFixed(2) + " MB"; }

console.log("Before:", mb(process.memoryUsage().heapUsed));

// Allocate roughly a few MB of strings:
let arr = [];
for (let i = 0; i < 100000; i++) arr.push("item-" + i);

console.log("After allocating:", mb(process.memoryUsage().heapUsed));

arr = null; // now unreachable - the GC may reclaim it later
console.log("Garbage collection runs automatically, in the background.");

libuv and the event loop

JavaScript in Node runs on one main thread. The trick that makes one thread enough is the event loop, provided by libuv. The loop repeats forever:

  • Run any timers whose time has come (setTimeout, setInterval)
  • Collect completed I/O (file reads, network data) and run their callbacks
  • Run setImmediate callbacks
  • Sleep until something new is ready

Slow operations never happen *on* the main thread. Network I/O is delegated to the operating system; file system work and CPU-heavy builtins (like some crypto functions) run on libuv's thread pool (4 threads by default). Either way, your JavaScript only sees the *completion callback*.

The loop, observed
console.log("1: synchronous code runs first, to completion");

setTimeout(() => console.log("4: timer callback (macrotask)"), 0);

Promise.resolve().then(() =>
  console.log("3: promise callback (microtask - before timers)"));

console.log("2: still synchronous");
// Order: 1, 2, 3, 4 - the loop only takes over
// after the current script finishes.

Blocking: the one rule you must respect

Because all JavaScript shares one thread, a long-running synchronous computation blocks everything — timers stop firing, requests stop being answered, the process appears frozen. This is the cardinal sin of Node programming.

  • Prefer asynchronous APIs (fs.promises.readFile) over sync ones (fs.readFileSync) in servers
  • Break up or offload CPU-heavy loops (worker threads — covered in the performance lesson)
  • Synchronous APIs are fine in short scripts and startup code, where nothing else is waiting
A blocked event loop
setTimeout(() => console.log("timer fired (wanted: ~50ms)"), 50);

const start = Date.now();
// Synchronously burn ~200ms of CPU - the loop can't run:
while (Date.now() - start < 200) { /* spinning */ }

console.log("blocked the thread for", Date.now() - start, "ms");
// The 50ms timer fires LATE - only after we stop blocking.

Putting it together

A useful mental model of a running Node process:

  • Your JavaScript executes on the main thread inside V8
  • When you start an async operation, Node hands it to libuv and returns immediately
  • libuv uses the OS (network) or its thread pool (files, crypto) to do the work
  • Completed work queues a callback; the event loop feeds callbacks to the main thread one at a time

Because only one callback runs at a time, you get concurrency without data races — no locks, no mutexes. The trade-off: keep every piece of JavaScript short, and never block.

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

Which component provides the event loop and async I/O in Node.js?