Events Module NodeJS
Event is one of the core concepts in nodejs. Even a lot of node core functionality is based on the concepts of events.
An event is basically a signal that something has happened in our application.
For example, In node we have a class called HTTP where it listens to a port for requests.
So whenever a request came to the server it raises an event and we respond to the event which is nothing but sending a response to the client.
In this way, many node packages use events module in their implementation.
Let's see how to implement the events module.
const EventEmitter = require('events'); // Event emitter is a class
const emitter = new EventEmitter(); // instance of the class
// Register a listener
emitter.on('messageLogged', function(){
console.log('listener called'); // This will print when we run this code
})
// Raise an event
emitter.emit('messageLogged');
Note: Order is so important here in the above code if we register a listener after calling the emit method nothing would have happened. when we call the emit method it iterates over all the registered listener and calls them synchronously.
** Event Arguments **
When we raise an event also if we want to send some data about that event. When we are raising an event we can send additional arguments to that event.
const EventEmitter = require('events'); // Event emitter is a class
const emitter = new EventEmitter(); // instance of the class
// Register a listener
emitter.on('messageLogged', function(arg){
console.log('listener called', arg); // This will print when we run this code
})
// Raise an event
emitter.emit('messageLogged',{'id': 1, 'url':'http://'});
In this way, we can send arguments with events.