← Back to Node.js Course | Chapter 2: Core Modules | Lesson 4 of 7

events module

The events module lets objects announce that something happened and lets other code react.

In this page:

  1. events module
Syntax
javascript
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('eventName', (arg) => {
  // handle event
});
emitter.emit('eventName', value);

events module

EventEmitter is the base of many Node classes. Call on to register a listener and emit to trigger it with arguments. once registers a listener that runs a single time, and off removes one. Emitting the special error event without a listener throws.

Note: Always attach an error listener to emitters that can fail.

Example: events module

javascript
const EventEmitter = require("events");
const bus = new EventEmitter();
bus.on("greet", (name) => console.log("Hello,", name));
bus.once("greet", () => console.log("first time only"));
bus.emit("greet", "Ada");
bus.emit("greet", "Linus");
console.log("listeners:", bus.listenerCount("greet"));

// Output:
// Hello, Ada
// first time only
// Hello, Linus
// listeners: 1

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Emitting error with no listener
  2. Adding listeners in a loop and leaking memory
  3. Expecting emit to be asynchronous
Chapter Summary
  • EventEmitter supports on and emit
  • once runs one time
  • Listeners run synchronously in order
  • Unhandled error events throw
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.