EventEmitter – NodeJs

The EventEmitter class is a built-in class in Node.js that allows you to create objects that can emit events and have other objects listen for and handle those events. It is a useful tool for implementing the publish/subscribe pattern in Node.js applications.

Here is an example of using the EventEmitter class to create a simple event emitter that emits a “greet” event when a “greet” method is called:

const EventEmitter = require('events');

class GreetingEmitter extends EventEmitter {}

const greetingEmitter = new GreetingEmitter();

greetingEmitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);

greetingEmitter.greet = function(name) {
  this.emit('greet', name);

greetingEmitter.greet('John'); // prints "Hello, John!"

In this example, the GreetingEmitter class extends the EventEmitter class and defines a greet method that emits a “greet” event. The event listener function passed to the on method is called with the name argument when the “greet” event is emitted.

You can also pass additional arguments to the emit method, which will be passed to the event listener function. For example:

greetingEmitter.on('greet', (name, age) => {
  console.log(`Hello, ${name}! You are ${age} years old.`);

greetingEmitter.greet = function(name, age) {
  this.emit('greet', name, age);

greetingEmitter.greet('John', 30); // prints "Hello, John! You are 30 years old."

The EventEmitter class is a powerful tool for implementing event-driven architectures in Node.js applications. It allows you to decouple different parts of your application and create flexible, reactive systems.