Module F-9·18 min read

The EventEmitter class, on/emit/once/removeListener, custom events, why streams and HTTP are built on EventEmitter, and memory leak prevention.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module F-9 — Event Emitters & Node's Event-Driven Core

What this module covers: The EventEmitter class is the foundation of Node.js's architecture. HTTP servers, file streams, database connections, WebSockets — they all inherit from EventEmitter. You have already used it without knowing it: every time you called server.listen() or req.on('data', ...), you were using an EventEmitter. This module explains how EventEmitter works, how to build your own, how to avoid the memory leak that trips up every developer, and how the pattern underpins Node.js internals. Understanding this bridges Foundation to everything in the Practitioner and Architect phases.


What Is an Event Emitter?

An EventEmitter is an object that:

  1. Lets you register named listeners — functions to call when a specific event occurs
  2. Lets you emit events by name — which synchronously calls all registered listeners

It is the observer pattern, built into the Node.js runtime.

An EventEmitter is a radio station, not a phone call — it broadcasts on a named frequency without knowing or caring who's tuned in. A Promise is a phone call — one caller, one answer, then it's over.

javascript

Simple enough. The power comes from the fact that the emitter and the listener are decoupled — the code that fires the event does not know who is listening, and the listener does not know when or why the event was fired.


Core EventEmitter API

javascript

Building Your Own EventEmitter Subclass

The real pattern: extend EventEmitter in your own classes. This is how Node.js HTTP servers, streams, and virtually every I/O object are built.

javascript

Output:

text

The caller does not need to know anything about the pipeline's internals. It just listens for named events.


The error Event Is Special

If an EventEmitter emits an 'error' event and there is no listener registered for it, Node.js throws the error and crashes the process. This is not optional — it is a design decision to force you to handle errors explicitly.

javascript

Any class extending EventEmitter should either:

  1. Register a default 'error' listener in the constructor, or
  2. Document clearly that callers must register one

The Memory Leak Warning

This is the single most common EventEmitter mistake. By default, Node.js warns if you register more than 10 listeners for the same event on the same emitter:

text

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.