Back to results for “Design Patterns in Java”
Node.js › Events & EventEmitter

How do you create a custom class that emits events by extending Node's built-in EventEmitter?

Beginner

Answer

A class extends EventEmitter (from node:events) to inherit its .on(), .emit(), .once(), and .removeListener() methods, letting instances of that class emit named events at appropriate points in their logic, with any code holding a reference to that instance able to subscribe to those events without needing any other coupling to the class's internals.
const EventEmitter = require('node:events');

class Order extends EventEmitter {
  complete() {
    this.status = 'completed';
    this.emit('completed', { orderId: this.id, timestamp: Date.now() });
  }
}

const order = new Order();
order.on('completed', (data) => console.log('Order completed:', data));
order.complete();
Real-world example An order-processing class emits a 'completed' event rather than directly calling notification and inventory-update functions from inside its complete() method, letting other parts of the application (like an analytics tracker) subscribe to that same event later without ever modifying the Order class itself.

Common follow-ups: What's the difference between .on() and .once() when subscribing to an event?;How would you check how many listeners are currently attached to a specific event on an EventEmitter instance?