How Node.js Handles Thousands of Requests
People say Node.js is single-threaded.
Yet, it handles thousands of requests, reads files, and makes API calls without stopping.
How does it work?
The answer is libuv.
libuv is a C library. It gives Node.js asynchronous and non-blocking I/O capabilities. JavaScript cannot read files or manage network sockets on its own. Node.js uses libuv to talk to your operating system.
Without libuv, JavaScript would stop every time you read a file. Your app would become unresponsive.
With libuv, the file reads in the background. JavaScript keeps running other code.
Example:
console.log("Start");
fs.readFile("data.txt", "utf8", (err, data) => { console.log(data); });
console.log("End");
Output: Start End (file contents)
Node.js prints "End" before the file finishes reading. It does not wait.
How libuv manages your code:
• The Event Loop: libuv runs the loop that checks if tasks are finished. It puts callbacks in a queue when tasks complete. • Thread Pool: JavaScript uses one thread. libuv uses a pool of worker threads. By default, this pool has 4 threads. These threads handle heavy tasks like:
- File system operations
- DNS lookups
- Compression
- Cryptography • Networking: libuv manages HTTP, TCP, and UDP sockets. This allows servers to handle many connections at once. • Timers: libuv handles setTimeout and setInterval.
The execution flow works like this:
- JavaScript runs your code.
- libuv takes heavy tasks to the background.
- JavaScript continues to the next line.
- libuv notifies the Event Loop when the task is done.
- The Event Loop runs your callback.
Think of a pizza shop.
Without libuv, you stand at the counter and ask "Is my food ready?" every ten seconds. You block the line.
With libuv, you order, sit down, and wait for a notification. You stay free to do other things until the pizza is ready.
Summary:
• JavaScript execution: V8 Engine • Event Loop: libuv • File I/O: libuv • Network: libuv • Timers: libuv
libuv is the engine that keeps Node.js fast.
