node js event emitter
The EventEmitter
is a class that is defined and exposed by the events
module in Node.js. It is a core feature of Node.js that allows multiple objects to listen to an event (a string) emitted by another object. The EventEmitter
class provides several methods to manage the event listeners and to emit the events. Here's a brief explanation of each step:
- Import the
events
module using therequire
function:
const EventEmitter = require('events');
- Create a new instance of the
EventEmitter
class:
const myEmitter = new EventEmitter();
- Register a listener for a specific event using the
on
method:
myEmitter.on('event', () => {
console.log('An event occurred!');
});
- Emit the event using the
emit
method:
myEmitter.emit('event');
- Optionally, you can pass arguments to the event listeners when emitting an event:
myEmitter.on('sum', (a, b) => {
console.log(a + b);
});
myEmitter.emit('sum', 2, 3);
- Remove a specific listener using the
removeListener
method:
const listener = () => {
console.log('Listener to be removed');
};
myEmitter.on('removeListenerExample', listener);
myEmitter.removeListener('removeListenerExample', listener);
This summary outlines the basic steps for using the EventEmitter
in Node.js, from importing the module to emitting and handling events.