Sobes.tech
Junior — Middle

Can you explain what an Event Emitter is in Node.js and how it is used for event handling?

sobes.tech AI

Answer from AI

Event Emitter in Node.js is an object that allows creating and handling events. It implements the "observer" pattern, where one object (the emitter) generates events, and others (listeners) respond to them.

Main points:

  • The EventEmitter class is in the events module.
  • You can create your own emitters by inheriting from EventEmitter.
  • Listeners are registered using the on or addListener method.
  • Events are triggered with the emit method.

Example usage:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

// Register a listener for the 'greet' event
myEmitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

// Generate the 'greet' event
myEmitter.emit('greet', 'Alexey');

As a result, when emit is called, all listeners for the greet event will be invoked with the provided arguments.

This allows building asynchronous and event-driven architecture in Node.js.