• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

NodeJS Events

Events

NodeJS applications are single-threaded and event-driven application. NodeJS supports concurrency via the concept of event and callbacks, as it is event-driven. The async function calls help NodeJS in maintaining concurrency throughout the application. Node uses observer pattern. NodeJS application has one main loop which waits and listens for events, and once any event is completed, it immediately initiates a callback function. Below diagram represents how the events are driven in NodeJS applications.

NodeJS Event Loop

One thing you must note here is that events look very similar to callback functions, but the difference lies in their functionalities. When an asynchronous function returns its results callbacks are invoked, while event handling completely works on the observer pattern. In NodeJS, the functions which listen to events act as observers. Whenever an event is triggered, its listener function automatically starts executing. NodeJS Event modules and EventEmitter class provide multiple in-built events which are used to bind events with event listeners.

Binding an Event to an Event Listener

										    
											// Import events module
											var myEvents = require('events');
											
											// Create an eventEmitter object
											var eventEmitter = new myEvents.EventEmitter();
											
										

Binding an Event Handler to an Event

										    
											eventEmitter.on('eventName', eventHandler);
											
										

Firing an Event

										    
											eventEmitter.emit('eventName');
											
										
										    
											var myEvents = require('events');
											var eventEmitter = new myEvents.EventEmitter();
											
											var registrationHandler = function registration() {
											    console.log('Registration succesful.');
												eventEmitter.emit('welcome');
											}
											
											eventEmitter.on('registration', registrationHandler);
											
											eventEmitter.on('welcome', function() {
											    console.log('Welcome to Tutorials Logic.');
											});
											
											eventEmitter.emit('registration');