Senior
Node.js is a single-threaded application. How does it handle multiple concurrent requests?
sobes.tech AI
Answer from AI
Node.js operates on a single-threaded Event Loop, which allows efficient handling of many concurrent requests without creating new threads for each.
Main mechanisms:
- Asynchronous input/output (I/O) operations do not block the Event Loop. For example, reading files, database queries, and network operations are performed in the background.
- When an operation completes, a callback or promise is invoked, and the Event Loop continues processing.
Thus, Node.js does not create a new thread for each request but uses a non-blocking asynchronous approach, enabling it to serve thousands of concurrent connections with minimal overhead.
Example:
const http = require('http');
const server = http.createServer((req, res) => {
// Asynchronous operation, e.g., reading from a database
someAsyncOperation().then(data => {
res.end(data);
});
});
server.listen(3000);
Here, the server does not block during the operation and continues to accept new requests.