EventEmitter basics
Local practice: Node.js 22.16.0 on Linux x64; proposed teaching baseline 26.13.1 remains untested. Copy only the listed files into a fresh disposable directory. No dependency installation or external services required. These are static Node.js examples, not verified ByteMind runner tasks.
Publish a stock update
import { EventEmitter } from 'node:events';const stock = new EventEmitter();stock.on('changed', count => console.log('stock', count));stock.once('changed', () => console.log('first update'));stock.emit('changed', 4);stock.emit('changed', 2);Run:
node main.mjsExpected stdout:
stock 4first updatestock 2Exit status: 0. Expected stderr: empty.
How it works
Create an emitter with new EventEmitter(). on(name, listener) registers a recurring listener; once registers a listener that is removed when it is invoked. emit(name, ...args) passes arguments to listeners in registration order for ordinary on registrations and returns whether listeners existed. off(name, listener) removes a matching registration using the same function identity. Multiple registrations are possible; prepended listeners alter the order. The emitter does not await returned promises.
Remove a named listener
import { EventEmitter } from 'node:events';const bus = new EventEmitter();const audit = value => console.log('audit', value);bus.on('saved', audit);console.log(bus.emit('saved', 8));bus.off('saved', audit);console.log(bus.emit('saved', 9));Run:
node main.mjsExpected stdout:
audit 8truefalseExit status: 0. Expected stderr: empty.
Common mistake
Registering an inline anonymous function and later passing a different anonymous function to off does not remove the original. Store the function reference if it has a lifecycle.
Practice
Register two stock listeners, remove one and predict the next emitted messages. Compare the boolean return from emit when no listener exists.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
EventEmitter basics — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
When do ordinary listeners run during emit?
How many times is a once listener called by two emissions?
What does emit return for an ordinary event with no listeners?