1 answer
Node.js uses a single-threaded, event-driven, non-blocking I/O architecture: one main thread runs JavaScript on the V8 engine, while the libuv library's event loop and thread pool handle I/O in the background.
Architecture (diagram in words)
Client requests
|
v
+--------------+ +--------------------------+
| Event Queue | ---> | Event Loop (single |
+--------------+ | thread, V8 runs JS) |
+-----------+--------------+
non-blocking task: handled | blocking I/O task
directly, response sent v
+--------------------------+
| libuv Thread Pool |
| (file system, DNS, |
| crypto, compression) |
+-----------+--------------+
| callback queued
v
back to Event Queue -> Event Loop
-> response to client
Components
- V8 engine: Google's JavaScript engine that compiles JS to machine code.
- Event queue: incoming requests and completed callbacks wait here.
- Event loop: continuously picks events from the queue. Simple (non-blocking) work is done immediately; slow I/O is handed off.
- libuv and thread pool: a C library providing asynchronous I/O; it uses OS async features (for network) or a small worker thread pool (default 4 threads, for file system, DNS, crypto). When a task finishes, its callback is placed back in the queue.
- Node.js bindings and core modules:
fs,http,path,events, etc.
Because the main thread never waits for I/O, one Node.js process can handle thousands of concurrent connections, which suits APIs, chat apps and streaming. CPU-heavy work, however, blocks the loop.
Program: create a text file with user data
const fs = require("fs");
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter the text to save: ", (data) => {
fs.writeFile("userdata.txt", data, (err) => {
if (err) {
console.log("Error writing file:", err.message);
} else {
console.log("File userdata.txt created successfully.");
}
rl.close();
});
});
Run with node app.js. The readline module reads the user's input; fs.writeFile creates (or overwrites) userdata.txt asynchronously and calls the callback when done, showing the non-blocking style described above.
Your answer
Log in or create a free account to answer this question.