Node.js EventEmitter Tutorial: Events, Listeners and Runnable Examples

Build a precise mental model of Node.js events with three runnable programs. Trace listener order, nested emits, removal, return values and common mistakes.

KnowledgeGate Team

Exam prep & CS education

Updated 8 Nov 20265 min read
Node.js EventEmitter Tutorial: Events, Listeners and Runnable Examples

Node.js uses events throughout its ecosystem, but on(), once() and emit() can look like an asynchronous queue at first. A basic EventEmitter actually calls matching listeners immediately, in registration order. A two-payment trace makes listener order, nested events, removal and the boolean returned by emit() observable. EventEmitter is an in-process API with behavior distinct from browser DOM events and message brokers.

1. Events and EventEmitter: the three-part mental model

An emitter is the object that announces something. An event name is a string such as score:updated. A listener is a function registered to run when that name is emitted. Any values after the event name become arguments to that listener.

The chain to remember is create emitter -> register listener -> emit name plus values -> invoke matching listeners. This is in-process publish and listen. It does not bubble through a DOM tree, persist messages, cross a network or replay an old event for a listener added later. For wider learning routes, use the Programming Languages and Web Development hubs.

2. Build the first EventEmitter and pass multiple values

Save this complete CommonJS program as first-emitter.js. It runs without a package.json module setting.

js
const { EventEmitter } = require('node:events');

const updates = new EventEmitter();

updates.on('score:updated', (name, before, after) => {
  console.log(`${name}: ${before} -> ${after}`);
});

console.log(`handled=${updates.emit('score:updated', 'Asha', 18, 23)}`);
console.log(`missing=${updates.emit('score:missing', 'Asha')}`);

Run node first-emitter.js. The exact output is:

Code
Asha: 18 -> 23
handled=true
missing=false

on() stores one listener under score:updated. The first emit() forwards Asha, 18 and 23, and the listener prints the change. It returns true because a matching listener existed. The second call returns false because score:missing has no listener. That false is not an exception.

3. Worked example: trace two payments, once() and a nested event

Now save this as payment-events.js and run it with Node.js:

js
const { EventEmitter } = require('node:events');

const bus = new EventEmitter();
const totals = { paid: 0 };

bus.once('order:paid', ({ id }) => {
  console.log(`first paid order: ${id}`);
});

bus.on('order:paid', ({ id, amount }) => {
  totals.paid += amount;
  console.log(`record ${id}: ${amount}`);
  bus.emit('receipt:ready', { id, runningTotal: totals.paid });
});

bus.on('receipt:ready', ({ id, runningTotal }) => {
  console.log(`receipt ${id}; running total ${runningTotal}`);
});

console.log('A before');
console.log(`B listeners=${bus.listenerCount('order:paid')}`);
console.log(`C handled=${bus.emit('order:paid', { id: 'KG-1042', amount: 750 })}`);
console.log(`D listeners=${bus.listenerCount('order:paid')}`);
console.log(`E handled=${bus.emit('order:paid', { id: 'KG-1043', amount: 250 })}`);
console.log(`F total=${totals.paid}`);
console.log(`G missing=${bus.emit('order:missing', 'KG-1044')}`);

The program prints exactly 12 lines:

Code
A before
B listeners=2
first paid order: KG-1042
record KG-1042: 750
receipt KG-1042; running total 750
C handled=true
D listeners=1
record KG-1043: 250
receipt KG-1043; running total 1000
E handled=true
F total=1000
G missing=false

Start with totals.paid = 0. The first payment changes it from 0 to 750: 0 + 750 = 750. The regular listener emits receipt:ready with that running total. The second payment changes the value from 750 to 1000: 750 + 250 = 1000. Both order:paid calls return true; the unhandled order:missing call returns false.

Listener registry beside a synchronous call trace for the order:paid example, with the nested receipt:ready emit and missing=false.

4. Why the output has that order: listeners, once() and off()

At checkpoint B, two order:paid listeners exist. The once() listener was registered first, so it prints first, then its one call is consumed. The regular listener adds 750, prints its record and emits receipt:ready. That nested listener finishes before the outer emit() returns, so the receipt appears before C handled=true.

At D, only the regular listener remains. It adds 250, emits the second receipt and leaves totals.paid at 1000. No listener matches order:missing, so G is false.

Removal needs the same function object:

js
const audit = data => console.log(data.id);
bus.on('order:paid', audit);
bus.off('order:paid', audit);

Calling off('order:paid', data => console.log(data.id)) creates another function. It does not remove audit, even though the code looks similar.

State table of listener count, running total, last nested event and emit return at each checkpoint of the two-payment example.

5. EventEmitter is synchronous unless the listener schedules later work

A resolved Promise separates immediate listener execution from a later microtask:

js
const { EventEmitter } = require('node:events');

const emitter = new EventEmitter();
emitter.on('tick', () => console.log('listener'));

console.log('start');
emitter.emit('tick');
Promise.resolve().then(() => console.log('microtask'));
console.log('end');

Its output is:

Code
start
listener
end
microtask

The listener runs inside emit('tick'). The promise callback runs only after the current JavaScript stack finishes. Event-driven design and asynchronous scheduling are related, but EventEmitter does not make every listener asynchronous.

An expensive listener therefore blocks the caller until it returns. An async listener returns a promise, but ordinary emit() still returns its listener-present boolean and does not await that promise. Handle promise failures deliberately inside the listener or through a tested application-level error path.

6. Error events and five common EventEmitter mistakes

The error event needs special care. Emitting it without a matching handler can terminate the process. Register a handler for it and keep the failure path controlled:

js
bus.on('error', error => {
  console.error(`bus error: ${error.message}`);
});
bus.emit('error', new Error('payment declined'));

Its controlled output is bus error: payment declined.

Mistake

Consequence

Correction

Emit before registering

A later listener misses the past event

Register first

Remove with a different function

The original listener stays active

Keep and pass the original reference

Register one callback twice

It runs twice

Prevent unintended duplicate registration

Assume emit() awaits an async listener

Work outlives the caller's expectation

Handle promises explicitly

Mutate a shared payload

A later listener sees changed data

Pass immutable or copied data where isolation matters

Many listeners can trigger a warning that helps expose possible listener leakage. It is not a business rule saying only a fixed number may ever exist. For a related Node.js ecosystem topic, read Mongoose Schemas and Models.

7. How tests and interviews probe EventEmitter, plus three exercises

Common questions ask you to predict output order, distinguish on() from once(), read the boolean from emit(), decide whether a late listener runs, find why off() failed, or separate immediate calls from timers and microtasks.

Rapid check: listeners before the first payment = 2; listeners after it = 1; first receipt total = 750; second receipt total = 1000; order:paid return = true; order:missing return = false; ordering = start, listener, end, microtask.

Try these before reading each answer:

  1. Change the second amount from 250 to 300. Answer: the final total is 1050, because 750 + 300 = 1050.

  2. Move the once('order:paid', ...) registration below both payment emits. Answer: it prints nothing because EventEmitter does not replay old events.

  3. Save the receipt listener as const receipt = ..., then call off('receipt:ready', receipt) after the first payment. Answer: the second record line still prints, but the second receipt line does not.

8. The short version and the next deliberate step

Keep this chain: on or once registers -> emit matches the name -> listeners run synchronously in registration order -> nested emits finish before the caller continues -> once removes itself -> emit reports whether a listener existed. Rebuild the payment example, predict all 12 lines, then add and remove one named audit listener.

Continue with the Node.js, Express.js and MongoDB course, take the broader MERN Stack course, or browse Coding & Skills.