CPCODELAB
Node.js

Events & EventEmitter

9 min read

Events & EventEmitter

Node.js is built around an event-driven architecture. The events module provides the EventEmitter class, which is the backbone of most Node.js core APIs — streams, HTTP servers, and file watchers all inherit from it.

js
const EventEmitter = require("events");

// Create an emitter
const emitter = new EventEmitter();

// Register a listener
emitter.on("data", function(payload) {
  console.log("Received data:", payload);
});

// One-time listener
emitter.once("connect", function() {
  console.log("Connected! (fires only once)");
});

// Emit events
emitter.emit("connect");
emitter.emit("connect"); // Second emit — listener already removed
emitter.emit("data", { userId: 42, name: "Alice" });

Extending EventEmitter

In real applications you extend EventEmitter to give your own classes event capabilities. This pattern is used by Node.js streams, HTTP servers, and many popular npm packages.

js
const EventEmitter = require("events");

class DataPipeline extends EventEmitter {
  process(items) {
    this.emit("start", { count: items.length });
    for (const item of items) {
      // Process each item...
      this.emit("item", item);
    }
    this.emit("done");
  }
}

const pipeline = new DataPipeline();
pipeline.on("start", function(info) { console.log("Processing", info.count, "items"); });
pipeline.on("item", function(item) { console.log("Processed:", item); });
pipeline.on("done", function() { console.log("All done!"); });

pipeline.process(["a", "b", "c"]);

By default, Node.js warns if you add more than 10 listeners to a single event. Call emitter.setMaxListeners(n) to increase the limit for valid use cases.

Ready to test yourself?
Practice Node.js— quiz & coding exercises