What is Node.js?
Node.js provides simplicity in development because of its non-blocking I/O and even-based model results in short response time and concurrent processing, unlike other frameworks where developers have to use thread management.
Some facts about Node.js
- The node package manager (NPM) provides access to hundres of thousands of resuable packages.
- There’s a huge community that maintains Node.js and third party packages
- Node.js is portable. It is available on Microsoft Windows, MacOS, Linux and many others OS
- Node.js is a single-threaded but it can support concurrency via the concept of event and callbacks.
- Node.j uses the Observer pattern.
What is the Event Loop in Node.js
The Event Loop is what allows Node.js to perform non-blocking I/O operations despite the fact that is single-threaded.
Whenever a task gets completed, the Event Loop fires the corresponding event which signals the event-listener function to execute.
It is used to handle all the I/O operations in an asynchronous manner without blocking the main thread.
Whatever is async is managed by Event Loop using a queue and listener.
So when an async function needs to be executed, the main thread sends it to a different thread allowing V8 to keep executing the main code. Event Loop involves different phases with specific tasks such as timers, pending callbacks, idle or prepare, poll, check, close callbacks with different FIFO queues. Also in between iterations it checks for async I/O or timers and shuts down cleanly if there aren’t any.
So for example, if some network call needs to happen it will be scheduled in the event loop instead of the main thread (single thread). And if there are multiple such I/O calls each one will be queued accordingly to be executed separately (other than the main thread).
Thus even though we have single-threaded, I/O operations are handled in a non-blocking way.