When people first hear that Node.js is single-threaded, they often ask:
"If Node only has one thread, how can it read files, make HTTP requests, or talk to a database without freezing everything?"
It’s a great question — and the answer lies in how Node.js cooperates with the operating system (OS) and its internal library libuv. Let’s break it down.
Node.js is single-threaded in terms of running JavaScript, but it’s not “alone.” It relies on:
So when you make an HTTP request or read a file:
In more traditional programming languages like C or Java, if you call a function like read()
on a file or recv()
on a socket, the calling thread blocks until the data is ready.
But in Node.js, when you call:
fs.readFile("data.txt", (err, data) => {
if (err) {
console.error("File read failed:", err);
return;
}
console.log("File read complete");
});
the main JavaScript thread doesn’t stop and wait. Instead, it keeps running other code, can receive HTTP requests and handle them, and the callback fires later when the file is ready.