Node ~ Events Module - rohit120582sharma/Documentation GitHub Wiki

Node JS platform follows Events Driven Programming model. In Node JS applications, every operation generates an event and it has some Event Handlers to handle those events. In other words, something that has happened in our app that we can respond to is called Event and the code that responds to an event is called Event Listener.

For example, take Node JS File System Module. When the Node JS application tries to open a file, then it generates an event. If it finishes reading data from a file using ReadStream, then it generates another event. If it finishes writing data to a file using WriteStream, then it generates another event. Like this for every action in Node JS application, it generates an event.

EventEmitter

Node JS “events” module has one and only one class to handle events: EventEmitter class. It contains all required functions to take care of generating events. Generating events is also known as Emitting as it emits events in Node JS Platform. Many of Node’s built-in modules inherit from EventEmitter.

The concept is quite simple: emitter objects emit named events that cause previously registered listeners to be called. So, an emitter object basically has two main features:

  • Emitting name events
  • Registering and unregistering listener functions

It’s kind of like a pub/sub or observer design pattern.

var events = require('events');
var eventsEmitter = new events.EventEmitter();

eventsEmitter.on('myclick', (msg)=>{
	console.log(msg);
});
eventsEmitter.emit('myclick', 'This is message on emitting "myclick" event');

Process steps:

  • When Node.js application starts or ends an operation, EventEmitter class generates events and places them into Event Queue.
  • Event Queue maintains a queue of events.
  • Event Loop continuously waits for new events in Event Queue. When it finds events in Event Queue, it pulls them and tries to process them. If they require IO Blocking operations or long waiting tasks, then assign respective Event Handlers to handle them.
  • Event Handlers are JavaScript Asynchronous Callback Functions. They are responsible to handle events and return results to Event Loop.
  • Event Loop will prepare results and send them back to the Client.

⚠️ **GitHub.com Fallback** ⚠️