3 BACKEND API

Node.js Internals

⚙️ Node.js Internals: Beyond the Browser

For the first 20 years of its life, JavaScript was trapped inside the web browser. It could manipulate HTML buttons, but it physically could not read a file from your hard drive or open a network port to listen for incoming internet traffic.

In 2009, Ryan Dahl ripped the V8 JavaScript Engine out of Google Chrome, wrapped it in a C++ program called libuv, and created Node.js. Suddenly, JavaScript could build backend servers capable of handling millions of concurrent connections.


1️⃣ The Node.js Architecture

Node.js is not a framework or a language. It is a Runtime Environment.

The V8 Engine

Written in C++ by Google. It takes your raw text (let x = 5) and mathematically compiles it down into literal 1s and 0s (Machine Code) that your CPU can physically execute.

Libuv (The Magic of Asynchronous I/O)

This is the heart of Node.js. libuv is a C++ library that handles the Event Loop and background Thread Pool. It is the reason Node.js is famous for being "Non-Blocking".


2️⃣ The Event Loop and Non-Blocking I/O

Traditional backend languages (like PHP or Ruby) are Blocking/Synchronous. If a user requests a 5-megabyte database file, the entire server process halts and waits for the hard drive to spin and find the file. If user #2 connects during that 1-second wait, they are put on hold. To serve 1,000 users, Apache servers had to spawn 1,000 separate, heavy memory threads.

Node.js is Single Threaded, but Non-Blocking.

const fs = require('fs');

console.log("1. Starting Program");

// Asynchronous, Non-Blocking File Read
fs.readFile('/massive-database.json', (err, data) => {
    console.log("3. Finished reading the massive file!");
});

console.log("2. Moving on to other work...");

Output Order: 1, 2, 3.

How does this work? (The Event Loop)

When Node hits the fs.readFile command:

  1. The single JS thread hands the heavy reading task directly to libuv.
  2. libuv assigns a tiny background C++ thread to watch the hard drive.
  3. The main JS thread immediately moves to the next line (console.log("2")), keeping the server 100% responsive for new users.
  4. When the hard drive finishes 5 seconds later, libuv yells to the Event Loop.
  5. The Event Loop waits for the main JS thread to be empty, and shoves the callback function onto the stack, printing "3".

Because of this, a single Node.js thread can technically handle 10,000 simultaneous connections, as long as it isn't doing heavy CPU math.


3️⃣ CPU Bound vs I/O Bound Tasks

Node.js is flawless for I/O Bound applications (Input/Output).

  • Chat applications transferring text.
  • APIs fetching data from a database and returning JSON.
  • Video streaming.

Node.js is terrible for CPU Bound applications.

  • Rendering 3D graphics.
  • Calculating the millionth digit of Pi.
  • Converting a 4K video to 1080p.

If you block the single thread with 10 seconds of heavy CPU math, the Event Loop stops spinning. All 10,000 connected users instantly freeze and their requests time out.


4️⃣ Modules: CommonJS vs ES Modules

To build a massive server, you must split code into hundreds of files. Node.js historically used the CommonJS (CJS) module system, which differs from the React (ESM) syntax.

The Old Way: CommonJS (require)

// math.js
const add = (a, b) => a + b;
module.exports = { add }; // Pushing it out

// server.js
const math = require('./math.js'); // Pulling it in
console.log(math.add(5, 5));

The Modern Way: ES Modules (import)

In modern Node (v14+), you can use the exact same import/export syntax as React. You just have to add "type": "module" to your package.json file.

// math.mjs
export const add = (a, b) => a + b;

// server.mjs
import { add } from './math.mjs';

5️⃣ The Core Modules (Batteries Included)

Node.js ships with powerful integrated libraries interacting directly with the Operating System. You never have to npm install these.

  1. fs (File System): Reading, writing, and deleting physical files on the hard drive.
  2. path: Safely calculating file directory strings whether the server is on Windows (C: older) or Linux (/usr/folder).
  3. os: Reading the physical server's CPU cores, free RAM, and network interfaces.
  4. http: The raw, low-level module capable of opening port 80 and listening to web traffic. (We rarely use this directly anymore; we use Express instead).
  5. crypto: Hardware-accelerated cryptographic functions for hashing passwords and verifying SSL certificates.

💡 Summary Hierarchy

ConceptExplanationReal-World Impact
V8 EngineThe JS Compiler.Makes JS astronomically fast.
libuvThe C++ Async engine.Prevents the server from freezing during DB queries.
Event LoopThe traffic cop.Takes finished background tasks and executes their callbacks.
Single-ThreadedOnly one main lane.Unbeatable for high-concurrency APIs. Terrible for video editing.
CommonJSrequire()The legacy way Node imports files.
ESMimport {}The modern, React-aligned way to import files.

Knowledge Check

Complete this quick quiz to verify your understanding and unlock the next module.