🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Node.js Internals: V8, Modules and the Event Loop

Node.js FundamentalsđŸŸĸ Free Lesson
Node.js Fundamentals

The one-line mental model

Node.js gives you a single JavaScript thread plus a small pool of worker threads for blocking I/O, so a server can sit idle on ten thousand connections while only paying for the requests that are actually doing work.

You will leave this lesson able to trace a request through the event loop phases, convert a module between CommonJS and ES module syntax without breaking anything, read a lockfile critically, and spot the exact line in your own code that will freeze every connected client.

Prerequisites

  • !Comfortable with JavaScript functions, callbacks and promises
  • !Basic understanding of HTTP methods, status codes and headers

What You'll Learn

  • 1Explain what V8, libuv and the event loop each contribute
  • 2Choose CommonJS or ES modules deliberately and migrate between them
  • 3Interpret package.json ranges, lockfiles and npm scripts correctly
  • 4Build a raw HTTP server and reason about where it blocks

Why the runtime choice changes your design

Ryan Dahl built the first version of Node.js in 2009 around a plain observation: the dominant way to scale a server was to give every connection its own thread, and threads are expensive to create, expensive to switch between, and painful to share state across. Instead he took Chrome's V8 engine, which compiles JavaScript straight to machine code with just-in-time optimization, and paired it with libuv, a C++ layer that owns the event loop and a thread pool. The result is a runtime where waiting is free and computation is not.

Two consequences shape everything you will build. First, the language you already use in the browser works unchanged on the server, which is why a single team can share validation, types and tooling across the whole stack. Second, because there is exactly one JavaScript thread, any code that burns CPU for 200 milliseconds delays every other request in that process by 200 milliseconds. Most Node performance problems are not mystery latency, they are a synchronous JSON parse, a regex on a huge string, or a tight loop over a million rows sitting on the main thread.

How a request actually moves through the loop

When a request arrives, Node does not hand it to a waiting thread. The loop wakes up, runs your callback, and returns to poll the operating system for more work. The loop cycles through four phases in order: timers, where callbacks scheduled with setTimeout and setInterval run; pending callbacks, where certain OS-level operations complete; poll, where the loop retrieves new connection and I/O events; and check, where setImmediate callbacks fire. process.nextTick callbacks and promise microtasks drain between every phase, which is why they can starve the loop if you queue them in a recursion.

Blocking I/O such as reading a file or querying a database is offloaded to libuv's thread pool, which defaults to four threads. Your JavaScript call returns immediately, and the completion callback is queued once the pool finishes. That design has a sharp edge: four simultaneous blocking file reads mean a fifth waits. You can raise the pool size, but the better fix is usually an asynchronous driver or a stream that processes data in chunks. The same reasoning applies to promises: awaiting a database call yields the thread, while awaiting a busy loop over an array does not.

CommonJS and ES modules compared

Node supports two module systems, and mixing them carelessly is the most common source of "require is not defined" or "Cannot use import statement outside a module" errors at runtime.

TopicCommonJSES modules
Syntaxrequire() and module.exportsimport and export
LoadingSynchronous, resolved at runtimeResolved before execution begins
Static analysisDifficult, enables conditional requiresTrivial, enables tree shaking
Top-level thisEquals module.exportsEquals undefined
Directory helpers__dirname and __filename availableMust derive them from import.meta.url
File extensionAny .js file by defaultNeeds "type": "module" or .mjs

The practical rule is to pick one system per package and enforce it with the type field in package.json. A library that ships ESM while your application still requires it with CommonJS can fail in confusing ways, especially when the dependency itself imports CSS, JSON or native addons.

javascript
// CommonJS: values are copied at require time, so mutating exports later is risky
const legacy = require('./legacy-tools');

module.exports = {
  slugify(text) {
    return String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
  },
  // re-exporting keeps a stable shape for consumers
  helper: legacy.helper,
};

// ES modules: bindings are live and hoisted, so circular imports behave differently
import { slugify } from './tools.js';

export function titleCase(text) {
  return text.replace(/\b\w/g, (c) => c.toUpperCase());
}

console.log(slugify('Release Notes 2026')); // release-notes-2026

One subtle behavioural difference matters during refactors: CommonJS copies the exports object when you destructure it, whereas ESM imports are live read-only bindings. Code that mutates exports.name halfway through initialization works in one system and silently reads undefined in the other.

What npm writes to your disk

Running npm install does three things that are worth understanding rather than trusting. It reads the dependency ranges in package.json, resolves them to concrete versions, and records the full tree in a lockfile so every machine and CI runner reproduces the same result. Caret ranges such as ^4.18.2 allow minor and patch upgrades; tilde ranges such as ~4.18.2 allow only patches; an exact pin allows nothing.

{
  "name": "orders-api",
  "version": "1.4.0",
  "type": "module",
  "engines": { "node": ">=20" },
  "scripts": {
    "dev": "node --watch src/server.js",
    "test": "node --test",
    "start": "NODE_ENV=production node src/server.js"
  },
  "dependencies": { "fastify": "^4.28.0" },
  "devDependencies": { "vitest": "~1.6.0" }
}

In CI you should run npm ci instead of npm install: it deletes node_modules, installs exactly what the lockfile says, and fails loudly when package.json and the lockfile disagree. The lockfile belongs in version control; node_modules never does. Scripts defined under scripts are the standard way to hide long command lines, and npx runs a package binary without installing it globally, which keeps tool versions pinned to the project.

A server with no framework

Nothing in Node requires Express. The standard library ships an HTTP server, and building one once teaches you what every framework is doing for you.

javascript
import { createServer } from 'node:http';

const users = new Map([['42', { id: '42', name: 'Ada' }]]);

const server = createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');

  if (req.method === 'GET' && url.pathname.startsWith('/users/')) {
    const user = users.get(url.pathname.split('/').pop());
    const body = user ? JSON.stringify(user) : '{"error":"not found"}';
    res.writeHead(user ? 200 : 404, { 'content-type': 'application/json' });
    res.end(body);
    return;
  }

  if (req.method === 'POST' && url.pathname === '/users') {
    let raw = '';
    // accumulating the body by hand is exactly what express.json() automates
    req.on('data', (chunk) => { raw += chunk; });
    req.on('end', () => {
      try {
        const parsed = JSON.parse(raw);
        const id = String(users.size + 1);
        users.set(id, { id, name: parsed.name });
        res.writeHead(201, { 'content-type': 'application/json' });
        res.end(JSON.stringify(users.get(id)));
      } catch {
        res.writeHead(400, { 'content-type': 'application/json' });
        res.end('{"error":"invalid json"}');
      }
    });
    return;
  }

  res.writeHead(404).end('not found');
});

server.listen(3000, () => console.log('listening on http://localhost:3000'));

Reading this explains the value of a framework: routing tables, body parsing, header handling, error envelopes and middleware ordering are all things you would otherwise reimplement for every project.

Where Node fits — and where it does not

WorkloadFitReasoning
JSON APIs and GraphQL backendsExcellentMostly I/O waiting, small CPU slices
WebSockets and chat fan-outExcellentThousands of idle sockets cost almost nothing
File streaming and proxiesExcellentstream keeps memory flat on large payloads
Scheduled jobs and queuesGoodKeep each job short or move it to a worker
CPU-heavy transforms or model trainingPoorOne busy thread starves every request
Long synchronous database transactionsPoorBlocking the loop converts one slow query into a total outage

When a workload is CPU-bound, the two standard escapes are worker_threads, which gives you real parallel JavaScript with message passing, or moving the work to a separate service or job queue so the request path stays responsive.

Common Mistakes

Parsing a 50 MB JSON body synchronously on the request path

Fix: Stream the body, cap its size, and move heavy parsing to a worker or background job

Installing dependencies with npm install in CI

Fix: Use npm ci so the lockfile is the single source of truth and drift becomes a build failure

Mixing require and import in one package without setting type field

Fix: Declare module type once per package and keep every file in that system

Assuming more processes always means more throughput

Fix: Measure first; add workers only after you have removed main-thread CPU bottlenecks

Best Practices

  • Set an engines field and run the same Node major version locally, in CI and in production
  • Fail fast on unhandled rejections by attaching a top-level handler that logs and exits
  • Prefer built-in modules such as node:test, node:fs and node:crypto before adding dependencies
  • Keep secrets out of package.json and read them from the environment at boot
  • Expose a readiness endpoint so orchestrators do not send traffic before your server listens

Interview Questions

Q1: Why does a synchronous loop block every request in a Node.js process?

JavaScript runs on a single thread, so the event loop cannot poll sockets or drain the callback queue while your loop occupies it. Work must be chunked with setImmediate or moved to worker_threads.

Q2: What is the difference between setImmediate and setTimeout(fn, 0)?

setImmediate runs in the check phase of the current loop iteration, while a zero-delay timer is scheduled for the timers phase of the next iteration, so ordering between them depends on where the call happened.

Q3: How does npm ci differ from npm install?

npm ci discards node_modules, installs exactly the lockfile tree, verifies it matches package.json, and fails on mismatch, which makes builds reproducible.

Q4: When would you choose worker_threads over a child process?

Use worker_threads for CPU work that can share memory and stay in-process; use child processes for isolating crashes, native binaries or different runtime versions.

Key Takeaways

  • Node pairs V8 with libuv so I/O waits are handled by an event loop and thread pool, not by a thread per connection
  • One JavaScript thread means CPU-heavy code is the main availability risk in any Node service
  • CommonJS and ES modules differ in loading time, live bindings and directory helpers, so pick one per package
  • The lockfile, not package.json, defines what your machines actually run
  • Frameworks exist to standardise routing, body parsing, middleware order and error handling you would otherwise rewrite
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert Node.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement