Sobes.tech
Middle+

What is an EventEmitter and how does it work?

sobes.tech AI

Answer from AI

EventEmitter is a class in Node.js that implements the "publisher-subscriber" pattern. It allows objects to generate events and subscribe to them.

How it works:

  • An object inheriting from EventEmitter can call the emit method to generate an event with a name and arguments.
  • Other parts of the code can subscribe to these events using on or once, passing handlers.
  • When the event is called, all subscribed handlers are executed with the passed arguments.

Example:

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('message', (text) => {
  console.log('Received message:', text);
});

emitter.emit('message', 'Hello, world!');
What is an EventEmitter and how does it work? — Node.js - sobes.tech