What is the event loop, and why does it allow Node.js to handle many concurrent operations despite being single-threaded?
Short answer
The event loop is the core mechanism that lets Node.js perform non-blocking I/O -- it continuously checks for completed asynchronous operations (a finished file read, an incoming network request) and executes their associated callbacks, allowing a single JavaScript thread to…
Advertisement
AModel answer
The event loop is the core mechanism that lets Node.js perform non-blocking I/O -- it continuously checks for completed asynchronous operations (a finished file read, an incoming network request) and executes their associated callbacks, allowing a single JavaScript thread to juggle many in-flight I/O operations by never blocking while waiting for any one of them, instead delegating I/O work to the OS (or libuv's thread pool) and being notified when it's done.
console.log('1: Starting');
fs.readFile('file.txt', () => console.log('3: File read complete'));
console.log('2: This runs before the file read finishes');
// Output order: 1, 2, 3 -- the file read happens in the background
// while the main thread continues executing other codeReal-world example
A web server handling thousands of concurrent connections doesn't need a thread per connection like some traditional server architectures, since the event loop lets a single thread initiate many I/O operations (database queries, file reads) and handle whichever one completes first, without any of them blocking the others.
Likely follow-ups
- What specifically happens to a request if a piece of synchronous, CPU-heavy code runs during the event loop's processing?
- How does the event loop relate to and differ from multi-threading in a language like Java?
Related topics