Logo

Demystifying EventEmitter in Node.js

EventEmitter is a class that is built-in to the Node.js runtime. It provides an API for raising and handling events. In this article, we'll take a closer look at how EventEmitter works and how you can use it in your own Node.js applications.

How EventEmitter Works

At its core, EventEmitter is a simple class that provides methods for emitting and listening for events. When you create an instance of EventEmitter, you can use the on() method to register event listeners that will be executed when a specific event is emitted. Here's a simple example:

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

emitter.on('myEvent', (data) => {
  console.log(data);
});

emitter.emit('myEvent', 'Hello, world!');

In this code, we create an instance of EventEmitter and store it in the emitter variable. We then use the on() method to register an event listener for the 'myEvent' event. When this event is emitted, the callback function will be executed and will log the data that was passed to the emitter.emit() method to the console.

Common Internal EventEmitters in Node.js

EventEmitter is used extensively throughout the Node.js core. In fact, many of the built-in classes in Node.js are subclasses of EventEmitter, and they emit events to signal different things to your code.

Here are a few examples of internal EventEmitters in Node.js:

EventEmitters in Popular Node.js Frameworks

In addition to being used internally in Node.js, EventEmitter is also widely used in popular Node.js frameworks. Here are a few examples of how EventEmitter is used in popular Node.js frameworks: