Node.js is a server side java script framework. It is a single-threaded application, but it can support concurrency via the concept of event and callbacks. The event loop is what allows Node.js to perform non-blocking I/O operations, and this is what i am going to discuss in details.
What is event loop in Node.js :-
Node.js is pretty fast compared to other similar technologies, because it uses events heavily. Basically, as soon as Node server starts its wait for an events to occur and responds accordingly.
In an event-driven application, there is generally a main loop that listens for events and then triggers a callback function when one of those events is detected.
Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through the events module and EventEmitter class, which are used to bind events and event-listeners.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); // Create an event handler as follows var connectHandler = function connected() { console.log('connection successfull.'); // Fire the data_received event eventEmitter.emit('data_received'); } // Bind the connection event with the handler eventEmitter.on('connection', connectHandler); // Bind the data_received event with the anonymous function eventEmitter.on('data_received', function(){ console.log('data received succesfully.'); }); // Fire the connection event eventEmitter.emit('connection'); console.log("Program Ended."); |
1 2 3 |
connection successful. data received successfully. Program Ended. |
The following diagram shows a simplified overview of the event loop’s order of operations.
- timers: This phase executes callbacks scheduled by
setTimeout()
andsetInterval()
. - pending callbacks: Executes I/O callbacks deferred to the next loop iteration.
- idle, prepare: Only used internally.
- poll: Retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and
setImmediate()
), node will block here when appropriate. - check:
setImmediate()
callbacks are invoked here. - close callbacks: some close callbacks, e.g.
socket.on('close', ...)
.
Between each run of the event loop, Node.js checks if it is waiting for any asynchronous I/O or timers and shuts down cleanly if there are not any.
I hope you will find this blog useful. Please comments to make it even more better.
Recent Comments