What is EventEmitter in Node.js ?
EventEmitter is a class in node.js that is responsible for handling the events created using the ‘events’ module in node.js. Events are created to make custom operations while a set of operations is performed. EventEmitter can return two properties namely newListener if we want to create a new event listener and removeListener when we want to remove existing event listeners. Both of these mentioned properties emit an event whenever called to perform the operation.
In order to perform operations on EventEmitter, we need to create a reference using the ‘events’ module and then we need to initialize an instance of the EventEmitter so that we can use it further.
// Creating a constant reference of EventEmitter const EventEmittter = require('events'); // Initializing instance of EventEmitter var emitter = new EventEmitter();
Creating a listening event using addListener: Before we emit an event we have to create a listener who will listen to the callbacks emitted, then the listener will proceed with the further actions that are required to comply with the event. We can create an event listener with the help of the addListener property of EventEmitter. The addListener appends the event to the end of the array so we can call it multiple times to call multiple instances of the event and is very useful as we don’t require to write an event multiple times.
Emitting event: As every event is a named event in node.js we can trigger an event by using the emit method and we can pass arbitrary arguments to listen in the event.
Example: Code for creating an EventEmitter and adding events using addListener method.
Removing an instance of an event: We can remove an event using two methods removeListener if we want to remove a specific listener from the event or removeAllListeners if we want to remove an instance of all listeners from an event.
// For removing any single listener form the event emitter.removeListener(eventName, listener) // For removing all listeners of the event emitter.removeAllListeners(eventName)
Example: Code for removing the event listener of an event.
Message from person1: Event occurred Message from person2: Event occurred
As you can see in the above output event was triggered twice but the output came only once as we deleted the event listeners so no listeners were present while emitting the event a second time.