Understanding Event Emitters in Node.js: How and When to Use Them

Published: (December 24, 2025 at 09:09 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

What Are Event Emitters in Node.js?

Event Emitters in Node.js are a core part of its asynchronous, event‑driven architecture. They allow communication between different parts of an application by emitting named events and responding to them with registered callback functions.

How Do Event Emitters Work?

  • Node.js provides the events module with the EventEmitter class.
  • Objects derived from EventEmitter can register event listeners and emit events asynchronously.
  • Listener functions execute each time the event is emitted.

Example: Basic Usage

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

// Registering an event listener
emitter.on('greet', (name) => {
    console.log(`Hello, ${name}!`);
});

// Emitting the event
emitter.emit('greet', 'Alice'); // Output: Hello, Alice!

Common Use Case: Custom Logging System

Suppose you need a custom logging solution across different components:

  • Create a logger that emits events when something should be logged.
  • Attach listeners to process or store those log events.

Example

const EventEmitter = require('events');

class Logger extends EventEmitter {
    log(message) {
        this.emit('log', message);
    }
}

const logger = new Logger();

// Listen for log events
logger.on('log', (msg) => {
    console.log(`Log: ${msg}`);
});

logger.log('Server started'); // Output: Log: Server started

Summary

  • Use Event Emitters for loosely coupled communication between different parts of a Node.js application.
  • Ideal for custom events, streaming APIs, or building modular systems.

You can extend or reuse EventEmitter to create powerful, modular Node.js applications.

Back to Blog

Related posts

Read more »

Core Premise of Function in JavaScript

Is this a function in JavaScript? javascript function fiveSquared { return 5 5; } Technically, yes. However, fiveSquared lacks the reusability that a real‑world...

Function, Objects and Array In JS.

Functions A function is a block of code that performs a specific task and can be reused. There are three ways to define a function in JavaScript: 1. Function D...