Courses / Node.js: From First Script to Production / Chapter 5
Module 3 · Asynchronous and event-driven code · Chapter 5 of 27
Event-Driven Programming with EventEmitter
Builds on Getting Started: What Node.js Is and Running Your First Script and Asynchronous Programming: Callbacks, Promises and async/await. Next up: Core Modules: Files, Paths, Buffers, Crypto and util.
Part 1 · The event-driven model
Emitters and listeners
A cricket score page has to react when a wicket falls, whenever it happens. Node handles this kind of "tell me when something occurs" work with events.
In an event-driven program, you do not call the code that handles something. You say "when this happens, run this function", and the system runs it at the right time. The thing that announces what happened is an emitter. A function registered to hear one kind of announcement is a listener (also called a handler). The announcement itself has a name, such as 'request' or 'close', and may carry arguments.
This is the same idea as addEventListener in a browser: a button emits click, and your function listens for it. Node uses it for the same reason. It does not know when the next request, byte or timer will arrive, so you register what to do and let Node call you.
You have already used the pattern. A callback passed to setTimeout is a one-time listener for "this much time has passed". The difference with events is that a name can fire many times, and many listeners can hear one name.
The alternative is polling: asking again and again whether something has happened, for example reading a counter every 100 ms. Polling wastes work when nothing changed and reacts late when something did. An event costs nothing until the moment it fires, and then the listener runs straight away. That is why a Node server with thousands of idle connections stays quiet until one of them sends data.
Which Node objects emit events
Much of Node's core is built from emitters, so understanding them unlocks how those objects behave. Servers emit request and listening. Streams emit data and end. The process object emits exit and signals. A child process emits close. All of them inherit from one class, EventEmitter, from the node:events module.
The script checks four different objects against EventEmitter:
import { EventEmitter } from 'node:events'; import { createReadStream } from 'node:fs'; import { spawn } from 'node:child_process'; import { createServer } from 'node:http'; const checks = { process: process, 'fs read stream': createReadStream(import.meta.filename), 'child process': spawn(process.execPath, ['-v']), 'http server': createServer(), }; for (const [name, obj] of Object.entries(checks)) { console.log(name.padEnd(15), obj instanceof EventEmitter); } checks['fs read stream'].destroy();
process true fs read stream true child process true http server true
Output on Node 24.18.0.
All four are emitters. So the method names you learn in this chapter, on, once, emit and the rest, work on all of them.
A server as an emitter
An HTTP server shows the pattern clearly. The next script creates a server with no request function and attaches listeners for three events instead: listening, request and close. When the server is ready it sends itself a request with fetch, and then closes.
import { createServer } from 'node:http'; const server = createServer(); server.on('listening', () => console.log('event: listening')); server.on('request', (req, res) => { console.log('event: request', req.method, req.url); res.end('ok'); }); server.on('close', () => console.log('event: close')); server.listen(55603, '127.0.0.1', async () => { const res = await fetch('http://127.0.0.1:55603/score'); console.log('client got:', await res.text()); server.close(); server.closeAllConnections(); });
event: listening event: request GET /score client got: ok event: close
Output on Node 24.18.0. The server ran on port 55603.
The events came in the order the server lived through them: ready to accept connections, one request arrived, and finally the server closed. Passing a function to createServer, as in the getting started chapter, is a shortcut. It registers that function as a listener for request.
The request listener got two arguments, the request and the response, which is how an emitter hands data to listeners: whatever you pass after the event name in emit arrives as the listener's parameters.
One limit to keep in mind. Events are not queued for someone who joins late. A listener hears only events emitted after it was added, and nothing warns you about an event that nobody heard.
Check yourself
Is an event listener the same as a callback?
- It is a callback that is registered under an event name and can be called many times.
- A plain callback is usually passed once for a single result.
Which module provides the EventEmitter class, and name two core objects that inherit from it.
node:events.- For example HTTP servers, streams,
processand child processes.
A server's listening event fired before your code added a listener for it. Will your listener run?
- No. A listener hears only events emitted after it was added.
| Term | Meaning |
|---|---|
| Event | A named announcement that something happened, with optional arguments. |
| Emitter | An object that announces events. |
| Listener | A function registered to run when an event is emitted. |
| EventEmitter | The Node class that most emitters inherit from. |
Part 2 · EventEmitter basics
The core methods
A handful of methods covers most uses of EventEmitter, and each is short.
| Method | What it does |
|---|---|
on(name, fn) | Adds a listener. Also written addListener. |
once(name, fn) | Adds a listener that removes itself after the first call. |
off(name, fn) | Removes a listener you added earlier, matched by the same function. Also written removeListener. |
prependListener(name, fn) | Adds a listener at the front of the list instead of the end. |
emit(name, ...args) | Calls every listener of that name with the arguments, and returns true if there was at least one. |
listenerCount(name) | Returns how many listeners that name has. |
To remove a listener with off you need a reference to the exact function you passed to on. An inline arrow function cannot be removed later, because you have no name for it. Give the function a name or a variable when you will need to remove it.
Listeners also decide what this means. In a listener written with the function keyword, this is the emitter that called it, which is handy for methods that read the fields of the emitter. An arrow function does not get that this, so it uses whatever this surrounded it. Pick the form on purpose, and prefer a plain variable in a closure when in doubt.
emit is synchronous
The most important fact about emit is when the listeners run. emit calls every listener immediately, one after another, in the order they were added, and only then returns. There is no queue and no waiting.
The scene follows a score feed with three listeners, plus a setImmediate callback queued just before the emit. Watch the order: all three listeners run and the line after emit runs before the immediate callback gets its turn.
Watch for emit running every listener before the immediate
Read it as steps
All three listeners run on the same stack, before the immediate callback queued earlier.
The scene has the same order as a real run of that code, shown on the next page.
Running it
Here is the script from the scene, run for real:
import { EventEmitter } from 'node:events'; const bus = new EventEmitter(); bus.on('goal', () => console.log('listener 1')); bus.on('goal', () => console.log('listener 2')); bus.on('goal', () => console.log('listener 3')); setImmediate(() => console.log('immediate')); bus.emit('goal'); console.log('emit returned');
listener 1 listener 2 listener 3 emit returned immediate
Now a wider example with the other methods. It adds three listeners for a wicket event, one with once and one with prependListener, emits twice, and then checks counts and a removal.
import { EventEmitter } from 'node:events'; const feed = new EventEmitter(); feed.on('wicket', (who) => console.log('listener 1:', who)); feed.once('wicket', (who) => console.log('listener 2 (once):', who)); feed.prependListener('wicket', () => console.log('listener 0: first')); console.log('before emit'); const heard = feed.emit('wicket', 'Rahul'); console.log('after emit, returned', heard); feed.emit('wicket', 'Karthik'); console.log('no listeners ->', feed.emit('boundary')); console.log('wicket listeners left:', feed.listenerCount('wicket')); const noisy = () => console.log('noisy'); feed.on('six', noisy); feed.off('six', noisy); console.log('six listeners left:', feed.listenerCount('six'));
before emit listener 0: first listener 1: Rahul listener 2 (once): Rahul after emit, returned true listener 0: first listener 1: Karthik no listeners -> false wicket listeners left: 2 six listeners left: 0
The prepended listener ran first, and once ran on the first emit only, leaving two listeners for the second. Emitting a name with no listeners returned false without any error. off removed the noisy listener, so the count for six went back to zero.
A trap with async listeners
Because emit returns right after calling the listeners, it does not wait for an async listener to finish. An async function returns a promise as soon as it hits its first await, and emit ignores that promise.
import { EventEmitter } from 'node:events'; import { setTimeout as sleep } from 'node:timers/promises'; const bus = new EventEmitter(); bus.on('save', async (id) => { await sleep(20); console.log('listener finished', id); }); console.log('emit returned', bus.emit('save', 7)); console.log('emit is done, but the listener is not');
emit returned true
emit is done, but the listener is not
listener finished 7emit returned true and the next line ran before the listener finished its 20 ms wait. If code after emit depends on the listener's work, it is not safe. Wait on a promise instead, such as one from events.once, or have the listener report back with an event of its own.
There is a second risk. If an async listener throws, the error becomes a rejected promise that nobody handles. An option of the class, captureRejections, sends such rejections to the error event instead.
Check yourself
Two listeners are added to 'tick', then emit('tick') is called. Does emit return before or after the listeners run?
- After.
emitruns every listener synchronously, in the order added, then returnstrue.
You add an anonymous arrow function with on and want to remove it later. What is the problem?
offneeds the same function reference, and an inline arrow has no name to pass.- Store the function in a variable first.
An async listener fails after an await. Does emit throw?
- No.
emithas already returned; the failure becomes a rejected promise.
Part 3 · The error event and listener leaks
Why error is special
Most event names are only labels you invent. One name has a built-in rule: 'error'.
If you emit 'error' and nobody is listening, Node does not ignore it. It throws the error. If the argument is an Error object, that object is thrown. If it is anything else, such as a string, Node throws a new error with the code ERR_UNHANDLED_ERROR. The rule exists so that failures cannot vanish silently. Since an emitter can fail at any time and cannot return an error to a caller, 'error' is the one place to hear about it.
An uncaught throw ends the process. So a stream or a server that emits error with no listener can bring a service down. The fix is simple: for every emitter you do not fully control, such as a socket, a request or a stream, add an error listener.
import { EventEmitter } from 'node:events'; const job = new EventEmitter(); try { job.emit('error', new Error('disk full')); } catch (err) { console.log('thrown by emit:', err.message); } try { job.emit('error', 'plain text'); } catch (err) { console.log(err.code, '|', err.message); } job.on('error', (err) => console.log('handled:', err.message)); console.log('emit returned', job.emit('error', new Error('disk full')));
thrown by emit: disk full
ERR_UNHANDLED_ERROR | Unhandled error. ('plain text')
handled: disk full
emit returned trueOutput on Node 24.18.0.
The first two emits had no error listener, so each threw, and the try/catch caught them. The string was wrapped into an error with code ERR_UNHANDLED_ERROR. After a listener was added, the same emit was handled, returned true and the script went on.
Errors from async listeners
Earlier you saw that a rejected async listener is not caught by emit. The class has an option for that. new EventEmitter({ captureRejections: true }) makes Node watch the promises that listeners return. If one rejects, the rejection is sent to the 'error' event, which is then handled like any other.
import { EventEmitter } from 'node:events'; const bus = new EventEmitter({ captureRejections: true }); bus.on('save', async () => { throw new Error('database down'); }); bus.on('error', (err) => console.log('routed to error:', err.message)); bus.emit('save');
routed to error: database down
The async listener threw after being called, but the error did not become an unhandled rejection. It reached the error listener. The option is off by default, so turn it on when your listeners are async. Keep the error listener itself synchronous: the documentation advises against async error handlers, because the errors this option routes to error get no further catch handler, which avoids an endless loop.
Too many listeners
Every on call adds a listener and holds a reference to its function. A common bug is adding a listener each time some code runs, and never removing it. A page that attaches a listener on every request makes the list longer without limit. Memory grows, and each emit gets slower, because it calls every listener.
Node tries to catch this early. When more than 10 listeners are added to one event name on one emitter, Node prints a warning, MaxListenersExceededWarning. The limit is events.defaultMaxListeners, which is 10 here, and you can raise it for one emitter with setMaxListeners(n). The warning does not stop anything. It only warns you.
import { EventEmitter, defaultMaxListeners } from 'node:events'; console.log('default limit:', defaultMaxListeners); process.on('warning', (warning) => { console.log(warning.name); console.log(warning.message.split('. ').join('.\n')); }); const page = new EventEmitter(); for (let i = 1; i <= 11; i++) { page.on('click', () => {}); } console.log('listeners:', page.listenerCount('click'));
default limit: 10 listeners: 11 MaxListenersExceededWarning Possible EventEmitter memory leak detected. 11 click listeners added to [EventEmitter]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit
stdout only. Node also prints the same warning on stderr.
The eleventh on call triggered the warning. The script caught it through the warning event on process and printed its parts. The listener count shows 11.
Some emitters really do need more than 10 listeners. Raise the limit then, for that emitter. If you cannot say why you have so many, look for a missing off or a missing once.
Two methods help you investigate. eventNames() lists the names that currently have listeners, and listenerCount(name) tells you how many each has. Print them from a timer in a test run: a count that only ever grows is the leak.
Check yourself
A stream emits error and has no error listener. What happens?
- Node throws the error, and if nothing catches it, the process ends.
What does emit('error', 'disk full') throw when there is no listener, and why is it not the string itself?
- An error with the code
ERR_UNHANDLED_ERROR. - Only
Errorobjects are thrown as they are; other values are wrapped.
You see MaxListenersExceededWarning in a service. Is the program broken, and what do you do?
- It is a warning only, but it often means listeners are added repeatedly and never removed.
- Find where listeners are added, and remove them or use
once.
Part 4 · Building your own emitter
Extending EventEmitter
Your own classes can emit events too. An order tracker for a food-delivery app is a good example: many parts of the system care when an order changes state, but the tracker should not know who they are.
To make a class an emitter, extend EventEmitter and call super() in the constructor before you use this. After that, your methods can call this.emit(...), and anyone can call tracker.on(...). The class decides what events exist and what arguments they carry, and that list is part of its public interface, as much as its methods are. Document each event name, and the data that travels with it.
Events decouple the code that does something from the code that reacts. The tracker moves an order forward. Sending a notification, writing a log line and updating a dashboard are three listeners that the tracker never mentions. You can add a fourth later without touching the tracker.
Name events for what happened, in the past tense or as a plain noun: placed, delivered, closed, data. Avoid names that sound like commands, such as sendEmail, because that tells listeners what to do instead of what occurred, and ties the tracker to one consumer.
The missed-event trap
A natural idea is to announce the start of an order from inside the constructor. It does not work, and the reason follows from the rule that a listener hears only events emitted after it was added.
import { EventEmitter } from 'node:events'; class EagerTracker extends EventEmitter { constructor(id) { super(); this.emit('placed', id); } } const tracker = new EagerTracker(101); tracker.on('placed', (id) => console.log('heard placed', id)); console.log('listener added after the constructor ran');
listener added after the constructor ran
The placed event fired inside the constructor, before new had even returned. The caller had no way to attach a listener yet, so nobody heard it. The on call that came afterwards listened for events that were already in the past.
The fix is to defer the emit, so that it happens after the current code has finished and the caller has attached its listeners. In Node the usual tool is process.nextTick(fn), which runs fn right after the current operation and before the event loop moves on. The microtasks chapter explains how nextTick fits in with other queues.
A tracker that works
The tracker below defers its first event with process.nextTick. It moves an order through four states, emits a status event for each one, and emits done at the last. If someone advances a finished order, it emits error.
import { EventEmitter } from 'node:events'; const steps = ['placed', 'preparing', 'out for delivery', 'delivered']; class OrderTracker extends EventEmitter { #index = 0; constructor(id) { super(); this.id = id; process.nextTick(() => this.emit('status', steps[0])); } advance() { if (this.#index === steps.length - 1) { const err = new Error(`order ${this.id} is finished`); return this.emit('error', err); } this.emit('status', steps[++this.#index]); if (this.#index === steps.length - 1) this.emit('done', this.id); } } const order = new OrderTracker(101); order.on('status', (s) => console.log(`order ${order.id}: ${s}`)); order.once('done', (id) => console.log(`order ${id} complete`)); order.on('error', (err) => console.log('error:', err.message)); setImmediate(() => { for (let i = 0; i < 4; i++) order.advance(); });
order 101: placed order 101: preparing order 101: out for delivery order 101: delivered order 101 complete error: order 101 is finished
Output on Node 24.18.0.
The placed status reached the listener even though it was emitted from the constructor's deferred callback, because by then the listeners were attached. The done listener used once, so it ran a single time. The last advance found the order already finished and emitted error, which the error listener handled instead of crashing the program.
Two design habits come out of this. State changes go through methods, so the class controls when events fire. And any emitter that can fail should emit error, giving the caller one standard place to handle it.
Events also make a class easy to test. A test can attach listeners that push every event into an array, run a few method calls, and then compare the array with the list of events it expected. Because emit is synchronous, the array is complete the moment the method returns, with no waiting needed, apart from the one deferred first event.
Check yourself
Why does a listener added right after new Tracker() miss an event emitted inside the constructor?
- The event was emitted before the constructor returned, so no listener existed yet.
- Listeners hear only events emitted after they are added.
What is the usual way in Node to emit an event "later" so the caller can attach listeners first?
- Defer the emit with
process.nextTick(() => this.emit(...)).
A class extends EventEmitter, and its constructor sets this.id = id on the first line, before super(). What happens, and what is the fix?
- Creating an instance throws a
ReferenceError, becausethisdoes not exist until the parent constructor has run. - Call
super()before any use ofthis.
Part 5 · Events as promises and EventTarget
Waiting for one event
Sometimes you only want to wait until one event happens and then go on, for example until a server is listening. Writing that with once and a callback splits your logic in two. The events.once function gives you a promise instead.
await once(emitter, 'name') waits for the next emit of that name and resolves with an array of the emit's arguments. It also rejects if the emitter emits 'error' first, so a failed start is an exception you can catch.
import { once } from 'node:events'; import { createServer } from 'node:http'; const server = createServer((req, res) => res.end('hi')); server.listen(55604, '127.0.0.1'); await once(server, 'listening'); console.log('listening on port', server.address().port); const clash = createServer().listen(55604, '127.0.0.1'); try { await once(clash, 'listening'); } catch (err) { console.log('once() rejected:', err.code); } server.close();
listening on port 55604
once() rejected: EADDRINUSEOutput on Node 24.18.0.
The first server reached listening, and the code continued. The second server tried the same port, which was taken, so it emitted error with the code EADDRINUSE, and once rejected with it. This replaces an error listener plus a listening listener with straight-line code.
The missed-event rule still applies. once must be called before the event fires, or the promise waits forever. Here listen was called first, but the listening event is always emitted later, after the current code has finished, so await once(...) on the next line is safe. If you start something that could emit at once, create the promise first and trigger the action second.
Many events as an async loop
For events that keep coming, events.on(emitter, 'name') returns an async iterator. You read it with for await, and each loop turn is one emit, with the arguments as an array. The loop never ends by itself, because more events could come, so you stop it with an AbortSignal passed in the options.
import { on, EventEmitter } from 'node:events'; const feed = new EventEmitter(); const stop = new AbortController(); setTimeout(() => feed.emit('score', 'IND 54/1'), 10); setTimeout(() => feed.emit('score', 'IND 61/1'), 20); setTimeout(() => stop.abort(), 50); const scores = on(feed, 'score', { signal: stop.signal }); try { for await (const [score] of scores) { console.log('score:', score); } } catch (err) { console.log('loop ended by', err.name); } console.log('after the loop');
score: IND 54/1 score: IND 61/1 loop ended by AbortError after the loop
Two scores arrived and were printed. When the controller aborted at 50 ms, the loop threw an AbortError, which the catch handled, and the code continued. Note that events.on queues events that arrive while your loop body is busy, so a slow body does not make you lose events, though the queue can grow.
An abort is not the only way out. The close option names events that end the loop normally, with no error to catch:
import { on, EventEmitter } from 'node:events'; const feed = new EventEmitter(); setTimeout(() => feed.emit('score', 'IND 54/1'), 10); setTimeout(() => feed.emit('score', 'IND 61/1'), 20); setTimeout(() => feed.emit('end'), 30); for await (const [score] of on(feed, 'score', { close: ['end'] })) { console.log('score:', score); } console.log('loop ended by the end event');
score: IND 54/1 score: IND 61/1 loop ended by the end event
The end event closed the iterator, so the for await loop simply finished. That suits emitters that announce their own end, such as a stream or a feed that sends end.
Use events.once for "wait for the next one" and events.on for "handle each one". Both are optional: plain listeners are still fine and often simpler for event streams that run for the whole life of a program.
EventTarget compared with EventEmitter
Node also has EventTarget, the same class browsers use. In Node 24 AbortSignal, the MessagePort used by worker threads and the global WebSocket all inherit from it, which an instanceof EventTarget check in this lab confirmed. When you write code meant to run in both a browser and Node, EventTarget is the common ground.
| EventEmitter | EventTarget | |
|---|---|---|
| Add a listener | on, once, prependListener | addEventListener, with { once: true } for one call |
| Trigger | emit(name, ...args) | dispatchEvent(new Event(name)) |
| Listener receives | the arguments you passed | one Event object |
Special error rule | throws if no listener | none |
| Same listener twice | called twice | ignored: registered only once |
| Where it comes from | node:events, Node only | a web standard, also in browsers |
import { EventEmitter } from 'node:events'; const target = new EventTarget(); target.addEventListener('ping', (event) => { console.log('listener got', event.type, event instanceof Event); }); target.dispatchEvent(new Event('ping')); console.log(target instanceof EventEmitter); const emitter = new EventEmitter(); emitter.on('ping', (...args) => console.log('emitter args:', args)); emitter.emit('ping', 1, 'two');
listener got ping true false emitter args: [ 1, 'two' ]
Check yourself
What does await once(server, 'listening') do when the port is already in use?
- It rejects with the error the server emitted, because
oncerejects whenerroris emitted first.
How do you stop a for await loop over events.on(emitter, name)?
- Pass an
AbortSignalin the options and abort it; the loop then throws anAbortError.
A function takes an EventTarget. Which method do you use to trigger an event on it, and what does a listener receive?
dispatchEvent(new Event(name)).- The listener receives one
Eventobject, not separate arguments.
| Term | Meaning |
|---|---|
| Async iterator | An object you read with for await, one value at a time. |
| AbortSignal | A web-standard signal used to cancel an operation. |
| EventTarget | The web-standard event class, also available in Node. |
All chapters · Previous: Asynchronous Programming: Callbacks, Promises and async/await