events module
The events module lets objects announce that something happened and lets other code react.
In this page:
Syntax
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
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
- Emitting error with no listener
- Adding listeners in a loop and leaking memory
- 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: