How Node.js Works

The runtime that lets JavaScript run outside a browser, and the single-threaded, event-driven model behind it.

What is it?

JavaScript was built to run in a browser, reacting to clicks and typing. Node.js is a runtime that lets it run elsewhere, such as on a server handling HTTP requests. It pairs Chrome's V8 engine (which turns JavaScript into fast machine instructions) with features a browser doesn't have, like reading files and opening network connections.

What surprises people: Node runs your JavaScript on a single thread, one line at a time. It stays fast because most backend work (reading files, querying databases, waiting on the network) is waiting, not computing. Node hands the waiting off, does other work, and returns to your code when the result is ready.

That loop (run code, hand off anything that waits, run whatever is ready next) is the event loop.

Explain like I'm 10

Node.js is like one waiter serving a whole restaurant. Instead of standing at one table until the kitchen finishes, the waiter takes the order, moves to the next table, and comes back when each dish is ready. One waiter serves far more tables this way, as long as no single task (like arguing with a customer for twenty minutes) hogs their attention.

Examples

Blocking vs. non-blocking file reads

const fs = require("fs");

// Blocking: nothing else runs until this finishes
const data = fs.readFileSync("large-file.txt");
console.log("done reading");

// Non-blocking: Node moves on immediately, and runs
// this callback later, once the file is ready
fs.readFile("large-file.txt", (err, data) => {
  console.log("done reading");
});
console.log("this logs first, before the read finishes");

The sync version freezes the single thread until the disk read finishes. The async version hands the read off, keeps running other code, and returns when the result is ready.

Why this matters for a server

app.get("/report", (req, res) => {
  // While this database query is pending, Node is
  // free to handle other incoming requests on the
  // same single thread.
  db.query("SELECT * FROM big_table", (err, rows) => {
    res.json(rows);
  });
});

A slow database query for one user doesn't stop the server from answering other users meanwhile. The thread isn't sitting idle waiting for it.

How it works

Node runs your JavaScript on one main thread. When your code does something that waits (reading a file, querying a database, making an HTTP request), Node doesn't wait on the main thread. It hands the work to the operating system or to a background thread pool called libuv, and keeps running the next JavaScript.

When the background work finishes, its callback (or promise) goes into a queue. The event loop keeps checking: "is the main thread free, and is a finished callback waiting?" When both are true, it runs that callback.

That's how one Node process can have thousands of database queries or file reads "in flight" at once, while only running one line of your JavaScript at any instant.

Your code            Background (libuv / OS)
 ─────────            ───────────────────────
 fs.readFile() ──────▶  reading disk...
    │
    ▼
 (keeps running
  other requests)
                        disk read finishes
                              │
                              ▼
 callback queued ◀────────────
    │
    ▼
 event loop runs it
 once the thread is free

Why does it exist?

Older server designs often gave each connection its own thread. That works but gets expensive: thousands of connections mean thousands of threads, each with memory and scheduling overhead. Node handles huge numbers of I/O-bound connections (network and disk work, not heavy computation) on one thread by never letting it sit idle.

When to use it

Node fits backends that mostly wait on I/O: REST APIs, real-time apps (chat, live dashboards), and services that mostly move data between a client and a database or another service.

When not to use it

Node struggles with CPU-heavy work (image or video processing, large in-memory computation, hashing huge payloads), because it occupies the single thread and blocks everything else. Offload that work to worker threads, a separate service, or a language built for multi-threaded computation.

Common mistakes

  • Running a long, synchronous, CPU-heavy loop in a request handler, which freezes the server for every other user until it ends.

  • Assuming Node is multi-threaded because it handles many requests at once. Only the waiting happens concurrently, not your JavaScript.

  • Using a sync file method (like readFileSync) in a production request handler, blocking every other request while it runs.

Practice exercises

  1. Easy:

    Explain in one sentence why fs.readFile lets other code run sooner than fs.readFileSync.

  2. Medium:

    Write a snippet with three console.log calls (one before, one inside a setTimeout callback, one after) and predict the order they print.

  3. Hard:

    Explain why one expensive synchronous loop (like sorting a huge array) in a request handler slows responses for every other concurrent user, even though Node handles many requests.

Interview questions

Is Node.js single-threaded or multi-threaded?

Your JavaScript runs on one main thread, but Node hands I/O work (file access, network calls) to the operating system or a background thread pool, so it can handle many things concurrently.

What is the event loop?

The mechanism that keeps checking whether the main thread is free and whether background work has finished, and runs the matching callback when both are true.

Why is a CPU-heavy operation bad for Node.js performance?

It occupies the single main thread, so nothing else (including other users' responses) runs until it finishes. I/O work, by contrast, is handed off while it waits.

What is V8, and what job does it do inside Node.js?

V8 is Chrome's JavaScript engine. In Node it parses and runs your JavaScript as fast machine instructions. Node pairs it with APIs a browser doesn't need, like filesystem and networking.

What does libuv do, and why does Node need it if JavaScript runs on a single thread?

libuv provides Node's event loop and a thread pool for work the OS can't do asynchronously on its own (like some filesystem calls). It lets Node hand off waiting work without blocking the JavaScript thread, then tells that thread when the work is done.

Between `fs.readFileSync(...)` followed by a `console.log`, and `fs.readFile(..., callback)` followed by the same `console.log`, which logs first relative to the file finishing?

With readFileSync, the log runs only after the whole file is read, because the call blocks. With readFile, the log runs immediately, before the read finishes, because the call returns right away and the callback runs later.

Why doesn't a slow database query for one user necessarily block the server from responding to other users at the same time?

The query is handed to the database (and the background/OS layer waiting on it), not run on Node's main thread. The thread stays free for other requests while it waits.

A request handler runs a synchronous loop sorting a 10-million-item array. What happens to every other concurrent request while it runs?

They all stall. The main thread is busy with the loop, so it can't process the event loop's queue or any other JavaScript until the loop ends.

Why is it misleading to say "Node.js is multi-threaded because it can handle many requests concurrently"?

The concurrency comes from handing I/O waiting elsewhere, not from running your JavaScript on several threads. Your code still runs one line at a time; only the waiting happens in parallel.

What actually happens, mechanically, when your code calls an asynchronous function like `fs.readFile`?

Node starts the operation, hands it to the OS or a background thread pool (via libuv), and returns control so the next line runs. When the work finishes, its callback is queued and the event loop runs it once the main thread is free.

Why does Node.js tend to perform well for REST APIs and real-time apps, but poorly for heavy image or video processing done directly in a request handler?

REST APIs and real-time apps mostly wait on network or database I/O, which Node handles without blocking the thread. Image and video processing is CPU-bound and occupies the thread, blocking everything else while it runs.

What would you reach for instead of doing CPU-heavy work directly in a Node.js request handler?

Worker threads, a separate service or process for the computation, or a language built for multi-threaded computation. That keeps the main thread free for other requests.

One endpoint calls `JSON.parse` on a huge synchronous payload directly in its handler, and the whole server feels sluggish. Why could one endpoint slow down unrelated requests?

JSON.parse on a large payload runs synchronously on the main thread. While it parses, the event loop can't do anything else, so every other request, even to different endpoints, waits.

Why does the event loop need to check both "is the main thread free" and "is there a finished callback waiting," rather than running callbacks the instant their background work completes?

The main thread runs one thing at a time, so a finished callback can't interrupt running code. It waits in a queue until the thread is free, and then the event loop picks it up.

Compare a traditional thread-per-connection server design to Node's single-thread-plus-event-loop design. What cost does Node avoid at scale?

Thread-per-connection adds memory and OS scheduling overhead for every open connection, which gets expensive at thousands of connections. Node handles many connections on one thread by never leaving it idle on I/O, avoiding the cost of creating and scheduling huge numbers of threads.

Why is `fs.readFileSync` considered dangerous inside a production server's request handler, but safe in a one-off setup script?

In a request handler, blocking the single thread stalls every other request the process is serving. In a one-off script nothing else depends on that thread, so a brief block costs nothing.

If Node hands off waiting for I/O elsewhere, what part of the code still has to run entirely on the single main thread with no way around it?

Your own JavaScript logic: every computation, loop and synchronous call runs on the main thread. Only the waiting on external operations (disk, network, database) is handed off.

Three `console.log` calls: one before `setTimeout(fn, 0)`, one inside `fn`, and one right after the `setTimeout` call. What order do they print in?

First log, then third, then the one inside the callback. setTimeout always defers its callback until at least the current synchronous code finishes, even with a 0ms delay.

Why does Node.js pairing V8 with extra APIs matter — what could JavaScript not do inside a browser that Node needed to add?

For security, browser JavaScript is sandboxed: no direct filesystem access and no opening arbitrary server sockets. Node adds APIs like fs and net/http on top of V8 so the same language can do server work a browser never allows.

What's the relationship between "waiting" and "computing" in explaining why Node stays responsive under many concurrent connections despite being single-threaded?

Most backend work per request is waiting (on disk, network or a database), not computing. Node never lets the thread idle during that wait, so it does other requests' computing meanwhile. Many requests seem to progress at once, though computation still happens one step at a time.