EventEmitter (Node.js)

EventEmitter is a core Node.js class for the observer pattern: an object emits named events, and listeners registered with .on() run when those events fire. Many Node APIs (streams, servers) are built on it.

Node.js

EventEmitter lets objects broadcast that something happened and lets other code react, decoupling the two. You call emitter.on('event', listener) to subscribe and emitter.emit('event', ...args) to fire it, passing any data along to every registered listener synchronously in registration order.

It underpins much of Node: an HTTP server emits 'request', a readable stream emits 'data' and 'end', a process emits 'exit'. Understanding EventEmitter explains how these APIs work and lets you build your own event-driven components by extending the class.

Useful methods include once() (listen for a single occurrence), removeListener()/off() (unsubscribe), and emitter.emit('error') which, if no listener is attached, throws and can crash the process — so always handle 'error' events. Node warns when more than 10 listeners are added to one event, hinting at a possible leak.

Syntax

emitter.on("event", listener); emitter.emit("event", data);

Examples

JavaScript

const EventEmitter = require("events");
const bus = new EventEmitter();

bus.on("greet", name => console.log("Hello,", name));
bus.emit("greet", "Ada");

Output:

Hello, Ada

Learn it in a lesson

See also

Back to the Dictionary