EventEmitter: Node's Signal System

EventEmitter: Node's Signal System in JavaScript: In the browser, buttons emit events and you listen with .

Concept Explanation

In the browser, buttons emit click events and you listen with addEventListener. Node has the same idea for the server, powered by the EventEmitter class. An object can emit named signals, and any number of listeners can react — the emitter has no idea who's tuned in.

It's a radio tower: the tower broadcasts on a frequency ("data ready!") and every radio listening reacts. Streams, HTTP servers, and most of Node's core are built on top of EventEmitter.


Syntax or Core Structure

import { EventEmitter } from "node:events";

const tower = new EventEmitter();

// Tune in (subscribe)
tower.on("message", (text) => {
  console.log("Received:", text);
});

// Broadcast (publish)
tower.emit("message", "Hello listeners!");

The emit call runs every registered listener synchronously, in the order they were added.


Real World Example

The HTTP Server: http.createServer() returns an EventEmitter. Every incoming request fires a 'request' event — Express is essentially a friendly wrapper around listening to those events.


Common Mistakes

  • Leaking Listeners: Adding listeners in a loop without removing them triggers Node's "possible memory leak" warning. Use .off() / removeListener().
  • Swallowed Errors: If you emit an 'error' event with no listener, Node throws and crashes. Always handle 'error'.
  • Assuming Async: emit is synchronous — heavy listener work blocks everything else.

Best Practices

  • Use once() for One-Offs: tower.once('ready', ...) auto-removes itself after firing a single time.
  • Name Events Clearly: Use verbs like connection, close, data so intent is obvious.
  • Clean Up: Remove listeners when a component is torn down.

Practice Exercises

  1. The Broadcaster: Create an EventEmitter, subscribe two listeners to one event, and emit it once.
  2. The One-Shot: Use .once() and prove the listener only runs a single time.
  3. The Crash Test: Emit an 'error' event with no listener and watch Node crash — then fix it by adding a handler.