Sobes.tech
Middle

What do you know about the EventEmitter class in Node.js?

sobes.tech AI

Answer from AI

EventEmitter is a class in Node.js that underpins many built-in modules (such as http, fs) and is used to implement the event-driven model.

Main features:

  • Event subscription: Allows registering functions (handlers) that will be executed when a specific event occurs.
  • Event emission: Enables calling (emitting) events, triggering registered handlers.
  • Data passing: When emitting an event, any data can be passed to handlers.

Main methods:

  • emitter.on(eventName, listener): Adds a handler listener for the event eventName.
  • emitter.once(eventName, listener): Adds a one-time handler listener for the event eventName. It will be called only once upon the first occurrence of the event.
  • emitter.emit(eventName[, ...args]): Calls all handlers registered for the event eventName, passing them the arguments ...args.
  • emitter.removeListener(eventName, listener): Removes a specific handler listener for the event eventName.
  • emitter.removeAllListeners([eventName]): Removes all handlers for the event eventName. If eventName is not specified, removes all handlers for all events.

Example usage:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.on('event', (a, b) => {
  console.log('Event occurred!', a, b);
});

myEmitter.emit('event', 'argument a', 'argument b'); // Will output: Event occurred! argument a argument b

EventEmitter implements the "Observer" pattern. This allows building loosely coupled systems where components interact through events without knowing about each other's internal implementation.

What do you know about the EventEmitter class in… - sobes.tech