Node.js Architecture Tutorial: Runtime, Event Loop and Worked Examples
Build a three-route Node.js server, follow one file read from request to response, and learn why asynchronous I/O differs from CPU-heavy JavaScript.
KnowledgeGate Team
Exam prep & CS education

Node.js is often called a language, a framework and a server, while architecture diagrams add V8, libuv, an event loop and a worker pool without saying who does what. A runnable server with three routes makes the distinction concrete. The /io route carries 18 + 21 + 16 = 55 from an HTTP request to its response, while one main JavaScript thread coordinates I/O without waiting synchronously for it.
What Node.js is, and what it is not
JavaScript is the language. Node.js is a runtime that executes JavaScript outside a browser, and Express is an optional framework built on Node.js. A Node process can create an HTTP server directly with the built-in node:http module.
Browsers provide page APIs such as the DOM. Node provides server-side capabilities such as files, processes, streams and network servers. Both environments can execute JavaScript through an engine, but they expose different APIs. Understanding this split explains why an asynchronous file read can release the JavaScript call stack while a recursive calculation occupies it. The Web Development hub provides the wider context around servers, clients and web applications.
The Node.js architecture map: V8, Node APIs, libuv and the operating system
Start at the application and move down. Your code calls Node's JavaScript APIs. V8 parses, compiles and executes that JavaScript on the main JavaScript thread. Node's native bindings connect selected APIs to native facilities. Libuv provides the event-loop abstraction and a worker pool for operations that need it. The operating system supplies sockets, files and low-level I/O facilities.
This does not create one new thread per request. Network readiness is commonly observed through operating-system mechanisms, while regular file operations and selected library work can use libuv's worker pool. Either way, JavaScript receives the completion later as a callback.
For GET /io, the request reaches port 3000, the handler requests data.json, and the file supplies Asha with scores 18, 21 and 16. The callback calculates 18 + 21 + 16 = 55 and sends {"student":"Asha","total":55}. The earlier Node.js File System Tutorial: Read, Write and Manage Files with Runnable Examples owns reading, writing, appending, directory inspection and file-specific failures. This route uses one read only to expose the runtime hand-off from the request callback to libuv and back.

Build the runnable three-route server
Create two files in the same directory. Put exactly this one line in data.json:
{"student":"Asha","scores":[18,21,16]}Save the following as server.js. It uses CommonJS, so it needs no package.json module setting.
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
if (req.url === '/io') {
console.log('1 /io handler started');
fs.readFile(path.join(__dirname, 'data.json'), 'utf8', (error, text) => {
if (error) {
res.statusCode = 500;
res.end(JSON.stringify({ error: 'read failed' }));
return;
}
const { student, scores } = JSON.parse(text);
const total = scores.reduce((sum, score) => sum + score, 0);
console.log(`3 /io callback: total=${total}`);
res.end(JSON.stringify({ student, total }));
});
console.log('2 /io handler returned');
return;
}
if (req.url === '/cpu') {
res.end(JSON.stringify({ fib40: fib(40) }));
return;
}
if (req.url === '/health') {
res.end(JSON.stringify({ ok: true }));
return;
}
res.statusCode = 404;
res.end(JSON.stringify({ error: 'not found' }));
});
server.listen(3000, () => console.log('listening on 3000'));Run node server.js in one terminal. In another, run curl http://localhost:3000/io. The response is {"student":"Asha","total":55}. The server logs appear as 1 /io handler started, 2 /io handler returned, then 3 /io callback: total=55.
Trace the event loop and callback ordering
The /io flow is a sequence of state changes:
V8 enters the request callback and prints
1.fs.readFileregisters the file operation and returns control. The handler prints2, then leaves the call stack.While the read is pending, the event loop can select other ready work.
When the read completes, its callback becomes eligible to run. V8 parses the fixed JSON, reduces
18 + 21 + 16to55, prints3and ends the response.
The event loop is not one magical FIFO queue. Timers become eligible after their threshold, I/O callbacks run when their work is ready, setImmediate uses the check phase, and close callbacks have their own handling.
Try this deterministic microtask check:
console.log('A');
setTimeout(() => console.log('D timer'), 0);
Promise.resolve().then(() => console.log('C promise'));
console.log('B');Its output is A, B, C promise, D timer. The promise reaction runs after the current stack and before the next timer callback. Zero milliseconds means no earlier than eligible, not immediate execution.

Asynchronous I/O does not make CPU work non-blocking
Call curl http://localhost:3000/cpu. The exact response is {"fib40":102334155}. That recursive fib(40) calculation runs on the main JavaScript call stack. If a /health request arrives while the calculation is still running, its JavaScript handler cannot execute until the stack becomes free.
The /io route behaves differently. Its handler returns while the file read is pending, leaving the main stack available for other ready callbacks. The final file callback still runs on the main JavaScript thread.
The precise rule is that JavaScript execution is single-threaded by default, but the Node process can use operating-system I/O facilities and libuv workers. CPU-heavy JavaScript needs a deliberate design such as worker threads, separate processes or a job system. Adding asynchronous syntax alone does not move the calculation elsewhere.
Common architecture mistakes and runnable-example errors
In a request handler,
fs.readFileSyncblocks the JavaScript thread. Keep request-path I/O asynchronous.Assuming
setTimeout(fn, 0)runs immediately gives the wrong order. Zero is a minimum threshold.Treating the event loop as one queue hides phase and readiness rules. Reason from the API and callback type.
Saying the whole process has one thread ignores operating-system facilities and libuv workers.
asyncalso does not movefib(40)off the JavaScript stack.Excessive promise or
process.nextTickwork can postpone I/O by prolonging microtask processing.
EADDRINUSE means port 3000 is occupied, so stop that process or change both the server and curl port. ENOENT means data.json is missing from the script directory. ECONNREFUSED usually means the server is not listening. Keep the error branch's single res.end and return so it cannot send two responses.
How tests and interviews probe Node.js architecture
Durable questions ask you to distinguish runtime, language and framework, match the architecture components to their roles, trace callback order, and identify blocking code.
Rapid check: Handler engine: V8. File API entry point: Node core
fs. File read support: libuv worker pool and the operating-system file system./iototal:55./cpuresult:102334155. Synchronous logs before the timer:A,B. Unknown route status:404.
Now self-check three changes:
Change the scores to
[5,8,13]. Expect5 + 8 + 13 = 26.Use the synchronous read. The JavaScript stack stays blocked during the read.
Add a second resolved-promise callback. It runs before
D timer.
The earlier Node.js Event Loop Explained: Phases, Microtasks, and the Output Questions Interviewers Ask takes the phase-level view of nextTick, setImmediate, timer and I/O order, and queue draining. The A/B/C/D trace above establishes the smaller rule needed for the server: Promise reactions run before the eligible timer after the current stack clears.
The short version and the next deliberate step
Remember the chain: request becomes ready, V8 runs JavaScript, a Node API delegates eligible I/O, the stack is released, the completion callback returns, and the response ends. Rebuild /io from memory, then explain why its logs are 1, 2, 3 while its sum is 55.
Continue with the free Node.js, Express.js and MongoDB course, take the broader full-stack route through the MERN Stack course, or browse the Coding & Skills catalogue.
Keep learning
MongoDB Aggregation Pipeline: `$match` to `$group` with a Worked Example
Build one MongoDB aggregation pipeline step by step. Follow five fictional orders through filtering, array expansion, grouping, projection, and deterministic sorting.
Future Internet Explained: Architecture, a Worked IoT Example and Exam Traps
Learn how device, edge, network, cloud and application layers cooperate, then solve a smart-campus example for data reduction and control-loop latency.
Testing React Components: A Runnable Vitest and Testing Library Tutorial
Build and test a small React progress component from its initial render through completion. The examples use accessible queries, awaited actions, and an exact mock assertion.
React Performance Optimization Tutorial: Profiler, memo, useMemo, and useCallback Examples
Build one React lab, measure its render and calculation counts, then remove avoidable work while keeping typing responsive.





