Async I/O and events · Lesson 7 of 18
EventEmitter
Decouple producers from listeners, and understand synchrony and listener cleanup.
EventEmitter implements the Observer pattern: a producer emits a named event and data, while many listeners react without the producer knowing them. It suits in-process events such as order:created, not cross-server messaging.
Producer
emit(order)
Email listener
Analytics listener
const { EventEmitter } = require("node:events")
const bus = new EventEmitter()
bus.on("order", (id) => console.log("email", id))
bus.once("order", (id) => console.log("first-order", id))
bus.emit("order", 42)
bus.emit("order", 43)Listeners run synchronously in registration order inside emit. If a listener throws and nobody handles it, emit throws. Use once for one-shot work and off when a lifecycle ends to prevent leaks.
Quick question
How often does a once listener run after two emits?
Exercise
Create an emitter that totals score events and prints 12 after 5 and 7.
Expected output: 12
const { EventEmitter } = require("node:events")
const bus = new EventEmitter()
let total = 0
bus.emit("score", 5)
bus.emit("score", 7)
console.log(total)Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.