Node.js Events

In Node.js applications, Events and Callbacks ideas are utilized to give concurrency. As Node.js applications are single threaded and every API of Node js are asynchronous. So it utilizes async capacity to keep up the concurrency. Node utilizes eyewitness design. Node string keeps an event loop and after the culmination of any assignment, it fires the relating event which flag the event audience capacity to get executed.

Event Driven Programming

Node.js utilizes event driven programming. It implies when Node begins its server, it basically starts its factors, pronounces capacities and after that essentially trusts that event will happen. It is the one of the motivation behind why Node.js is truly quick contrasted with other comparable innovations.

There is a primary loop in the event driven application that tunes in for occasions, and after that triggers a callback work when one of those occasions is detected.

Difference between Events and Callbacks:

Although, Events and Callbacks look similar but the differences lies in the fact that callback functions are called when an asynchronous function returns its result where as event handling works on the observer pattern. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events and event listeners.

EventEmitter class to bind event and event listener:

  1. // Import events module  
  2. var events = require('events');  
  3. // Create an eventEmitter object  
  4. var eventEmitter = new events.EventEmitter();  

To bind event handler with an event:

  1. // Bind event and even handler as follows  
  2. eventEmitter.on('eventName', eventHandler);  

To fire an event:

  1. // Fire an event   
  2. eventEmitter.emit('eventName');   eventEmitter.emit('eventName');

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.