T8 Node.js · Lesson 5
Events and streams
Much of Node works by events: something happens, and every part that cares hears about it. Learn the EventEmitter that rings the bells and the listeners that answer them, the special error event, emitters of your own, and the streams that hand you a file a piece at a time.
- say what an event, an emitter and a listener are, and use on and emit with arguments
- listen once, remove a listener, and say in what order listeners run
- handle the error event, and say why an error event that nobody hears stops the program
- make an emitter of your own with a class that extends EventEmitter
- read a file as a stream, in chunks, with the data and end events, for await, and readline's lines
- write a file as a stream, and copy one stream into another with pipe
The back cover
Much of Node works like a railway station. A bell rings when a train arrives, and every porter who cares hears it and acts. Node's events work the same way, and its streams carry data in pieces, like carriages, instead of all at once.
These pages show the EventEmitter that rings the bells and the listeners that answer them. They show how to listen once, in order, or no more, and why the error event is special. They show emitters of your own, and streams that read and write files a piece at a time.
Before you start
The story: The bell nobody heard
At midnight the boiler gauge read too hot. It did what it had always done: it sent a runner to the stoker, then to the valve-keeper, then to the clerk, one after another.
The new valve-keeper, who started this week, was on nobody's list. The runner never came to him, and the valve stayed shut until dawn.
Foreman Tappet hangs a brass bell above the gauge. "A gauge should not have to know who cares," she says. "It rings its bell, and everyone who cares listens for that bell. Teach the hall to work by bells."
In the browser, a page does not keep asking whether a button was pressed. It hands the button a function, and the browser calls that function when the click happens. That is an event: something that happens, and code that runs because of it.
Node works the same way, and not only for clicks. A file has been read, a request has come in, a program is about to end: each is an event, and Node's own parts tell you about them by events. This lesson shows how, and how to make events of your own.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Events in the browser. | button.addEventListener("click", f) | Node's on is the same idea. |
| Callbacks. | setTimeout(() => {}, 0) | A listener is a callback. |
| The event loop. | setImmediate(f) | When a stream's events come. |
| Classes and extends. | class A extends B { } | An emitter of your own. |
| this in a function. | function () { this } | What a listener's this is. |
| Errors and try. | try { } catch (e) { } | The error event. |
| Promises and await. | await promise | Waiting for one event. |
| Reading a whole file. | fs.readFileSync(f, "utf8") | Streams read it in pieces. |
| Buffers and encodings. | <Buffer 62 6f> | What each piece is. |
| Error codes. | ENOENT | A stream's error event. |
By the end of this lesson you will be able to:
- say what an event, an emitter and a listener are, and use on and emit with arguments;
- listen once, remove a listener, and say in what order listeners run;
- handle the error event, and say why an error event that nobody hears stops the program;
- make an emitter of your own with a class that extends EventEmitter;
- read a file as a stream, in chunks, with the data and end events, for await, and readline's lines;
- write a file as a stream, and copy one stream into another with pipe.
How to follow this lesson
Every block runs on the page, in a small Node that keeps its files in the page's memory. Each has also been run in real Node 22, and both print exactly what you see, in the same order. Order matters in this lesson: watch which line prints first.
In one line
This lesson is about events: emitters and listeners, the error event, emitters of your own, and streams, which hand you a file a piece at a time.
Events, listeners and emit
At a glance
A station bell does not know who is listening. It rings, and whoever cares comes running. The bell does its one job, and the listeners do theirs.
In Node, an emitter is the bell. It announces an event by name with emit, and can pass details along with it. A listener, added with on, is a function that answers one event. When the event is emitted, every listener for it is called at once, in the order they were added, with the arguments that emit was given.
Take a guess: Does Node warn you if one event collects too many listeners?
Node's built-in module events gives one class, EventEmitter. An object made from it is an emitter: it can announce that something happened.
Each announcement has a name, such as ring. A listener is a function that the emitter calls when it announces that name.
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("ring", () => console.log("someone is at the gate"));
bell.emit("ring");
Terminal: node app.js
someone is at the gate
Two methods do the work. on(name, listener) adds a listener for the event called name. emit(name) announces the event: the emitter calls every listener for that name.
Nothing happens on its own. Without emit, the listener never runs.
A note on the rope: arguments
An emit can carry details. Every argument after the name is handed to each listener, in the same order:
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("ring", (who, times) => console.log(who, "rang", times, "times"));
console.log(bell.emit("ring", "gate 6", 3));
console.log(bell.emit("nothing"));
console.log(bell.listenerCount("ring"), bell.eventNames());
Terminal: node app.js
gate 6 rang 3 times
true
false
1 [ 'ring' ]
The answer of emit is true when the event had listeners, and false when nobody was listening. Ringing a bell that nobody listens to is not an error: the news is lost, and the program goes on.
listenerCount(name) counts the listeners of one event, and eventNames() lists the events that have any.
Several listeners
An event can have many listeners. Each one is called, in the order it was added:
app.js
const EventEmitter = require("events");
const gauge = new EventEmitter();
gauge.on("hot", (heat) => console.log("stoker: damp the fire at", heat));
gauge.on("hot", (heat) => console.log("valve-keeper: open the valve at", heat));
gauge.on("hot", () => console.log("clerk: write it in the ledger"));
gauge.emit("hot", 95);
Terminal: node app.js
stoker: damp the fire at 95
valve-keeper: open the valve at 95
clerk: write it in the ledger
The gauge does not know who listens, and does not need to. A new valve-keeper adds one listener, and the gauge's own code does not change. This is the whole point of events: the part with the news and the parts that act on it stay apart.
emit runs the listeners at once
This surprises many people. An emit is not like setTimeout. It calls the listeners at once, one after the other, and returns only when all of them have run:
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("ring", () => console.log("listener"));
console.log("before emit");
bell.emit("ring");
console.log("after emit");
Terminal: node app.js
before emit
listener
after emit
So an event is not, by itself, something that happens later. It is a way to call functions by a name. Node's own emitters, such as the streams later in this lesson, emit their events from the event loop, because that is when their news arrives.
| Method | What it does |
|---|---|
emitter.on(name, listener) | adds a listener for the event name |
emitter.emit(name, ...args) | calls every listener for name with args; true if there were any |
emitter.listenerCount(name) | how many listeners name has |
emitter.eventNames() | the names of the events that have listeners |
Worked example 1
A pump-house gauge reads pressures. Above 3, it should announce high, with the pump's name and its pressure. One listener prints a warning, and another counts the warnings.
What we have: three readings, each a pump's name and a pressure
What we need: a warning for each reading above 3, and the number of warnings
The plan: make an emitter; add the two listeners; emit high, with two arguments, for each reading above 3; print the count
app.js
const EventEmitter = require("events");
const gauge = new EventEmitter();
let warnings = 0;
gauge.on("high", (pump, pressure) => console.log(`warning: ${pump} at ${pressure}`));
gauge.on("high", () => { warnings += 1; });
const readings = [["pump 1", 2.5], ["pump 2", 3.5], ["pump 3", 4]];
for (const [pump, pressure] of readings) {
if (pressure > 3) gauge.emit("high", pump, pressure);
}
console.log(warnings, "warnings");
Terminal: node app.js
warning: pump 2 at 3.5
warning: pump 3 at 4
2 warnings
- The listeners are added first, so they hear every emit that follows.
- Each emit carries two arguments, and each listener takes what it needs: the first takes both, the second takes none.
- emit runs both listeners at once, so warnings is up to date when the last line prints.
Two warnings, for pump 2 and pump 3.
Check: Two of the three readings, 3.5 and 4, are above 3, and the count says 2.
A path that fails: emitting one array, gauge.emit("high", [pump, pressure]). The listener's pump is then the whole array and pressure is undefined, so it prints warning: pump 2,3.5 at undefined.
When you are stuck: A listener never runs
Check the spelling. ring and Ring are two different events.
Check that on comes before emit. A listener added after an emit misses it.
Print emitter.listenerCount(name) just before the emit. If it says 0, the listener is not on this emitter.
Your turn
What does emit give back when no listener was added for its event?Tap to reveal
- Nobody heard the news.
false.
In what order do three listeners of one event run?Tap to reveal
- Think of the hot example.
In the order they were added.
node -e 'const E = require("events"); const e = new E(); e.on("x", (a, b) => console.log(a + b)); e.emit("x", 2, 3)'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
5
- emit hands 2 and 3 to the listener.
- The listener adds them.
It prints 5.
Did you know?
A warning at 11 listeners
Node watches for listeners piling up. Its manual says that by default an EventEmitter prints a warning if more than 10 listeners are added for one event, a useful default that helps find memory leaks. The method setMaxListeners changes the limit for one emitter, and Infinity or 0 removes it. A program that adds a listener on every request, and never removes one, trips the warning quickly.
Why it fits here: It answers this topic's question: Node warns when more than 10 listeners pile up on one event, as that often means a leak.
Source: Node.js manual: Events
An older name for emitters
The idea behind EventEmitter is older than Node. Software designers call it the observer pattern: an object, the subject, keeps a list of its observers and tells them of every change, often by calling one of their methods. It is one of the 23 patterns of the 1994 book Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, called the Gang of Four.
Why it fits here: It names this topic's idea: an emitter and its listeners are the observer pattern, from the 1994 book Design Patterns.
Sources: Wikipedia: Observer pattern; Wikipedia: Design Patterns; Refactoring.Guru: Observer
In one line
An emitter announces events by name with emit; the listeners added with on are called at once, in the order they were added, with emit's arguments.
Listening once, in order, and no more
At a glance
Not every listener wants every ring. Some want to hear only the first, some want to go first, and some want to stop listening.
The method once adds a listener that runs one time and then removes itself. The method prependListener puts a listener at the front of the line. The method off removes a listener, but only when given the very same function that was added. And removeAllListeners clears an event of all its listeners, while events.once gives a promise of the next emit, for code that waits with await.
Take a guess: Can a for await loop wait for an event again and again?
The method on adds a listener that hears every emit, for as long as the program runs. Often you want less than that: one time only, or until some moment, or ahead of the others. Three more methods give that control.
once, and listeners at the front
app.js
const { EventEmitter } = require("node:events");
const bell = new EventEmitter();
bell.on("ring", () => console.log("first"));
bell.on("ring", () => console.log("second"));
bell.prependListener("ring", () => console.log("before both"));
bell.once("ring", () => console.log("only once"));
bell.emit("ring");
console.log("--");
bell.emit("ring");
Terminal: node app.js
before both
first
second
only once
--
before both
first
second
once(name, listener) adds a listener that removes itself the first time it is called. The first emit ran it; the second did not.
prependListener(name, listener) puts a listener at the front of the queue, so it runs before the ones already there. Everything else keeps the order in which it was added.
off: stop listening
To remove a listener, give off(name, listener) the very same function that on was given. It removes one copy. The method removeAllListeners(name) removes every listener of that event:
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
function hear() { console.log("heard"); }
bell.on("ring", hear);
bell.on("ring", hear);
bell.emit("ring");
bell.off("ring", hear);
bell.emit("ring");
bell.removeAllListeners("ring");
console.log(bell.emit("ring"), bell.listenerCount("ring"));
Terminal: node app.js
heard
heard
heard
false 0
The function hear was added twice, so the first emit printed heard twice. One off removed one of the two, so the second emit printed it once. After removeAllListeners, nobody listens, and emit says false.
off needs the same function, not one that looks the same. Two arrow functions with the same text are two different functions:
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("ring", () => console.log("ding"));
bell.off("ring", () => console.log("ding"));
bell.emit("ring");
console.log(bell.listenerCount("ring"));
Terminal: node app.js
ding
1
Nothing was removed. To be able to remove a listener later, keep it in a name, as hear was kept, and give that name to both on and off.
this inside a listener
Inside a listener written with the word function, this is the emitter. An arrow function has no this of its own: it keeps the this of the code around it, which at the top of a CommonJS file is module.exports.
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("ring", function () { console.log(this === bell); });
bell.on("ring", () => console.log(this === bell, this === module.exports));
bell.emit("ring");
Terminal: node app.js
true
false true
Waiting for one event with await
The module's own function events.once(emitter, name) gives a promise. It is fulfilled the next time the event is emitted, with an array of the event's arguments. With await, code can wait for one event and read on from top to bottom:
app.mjs
import { EventEmitter, once } from "node:events";
const bell = new EventEmitter();
setTimeout(() => bell.emit("ring", "gate 6", 3), 10);
const args = await once(bell, "ring");
console.log(args);
Terminal: node app.mjs
[ 'gate 6', 3 ]
| Method | What it does |
|---|---|
emitter.once(name, listener) | adds a listener that runs one time, then removes itself |
emitter.prependListener(name, listener) | adds a listener at the front |
emitter.off(name, listener) | removes one copy of that very function |
emitter.removeAllListeners(name) | removes every listener of name |
events.once(emitter, name) | a promise of the next emit's arguments, as an array |
Worked example 2
The hall's start bell may ring several times. A warm-up listener must run only on the first ring, while a counter hears every ring.
What we have: an emitter called hall, and three rings of start
What we need: the boiler warmed once, and a count of 3
The plan: add the warm-up listener with once and the counter with on, ring three times, then print the count and the listeners left
app.js
const EventEmitter = require("events");
const hall = new EventEmitter();
let rings = 0;
hall.once("start", () => console.log("warming the boiler"));
hall.on("start", () => { rings += 1; });
hall.emit("start");
hall.emit("start");
hall.emit("start");
console.log("rings:", rings, "listeners left:", hall.listenerCount("start"));
Terminal: node app.js
warming the boiler
rings: 3 listeners left: 1
- The once listener ran on the first ring and removed itself.
- The counter, added with on, heard all three rings.
- One listener is left, the counter.
The boiler was warmed once, and the counter says 3.
Check: Count the lines: one warming line for three rings, and listenerCount says 1, the counter alone.
A path that fails: adding the warm-up listener with on and later removing it with off and a new arrow function. That arrow is a different function, nothing is removed, and the boiler is warmed three times.
When you are stuck: A listener runs too often, or after it should have stopped
For a listener that should run one time, use once.
off needs the very same function that on was given. Keep the function in a name.
Print emitter.listenerCount(name) to see how many listeners are left.
Your turn
Which method adds a listener that runs only the next time?Tap to reveal
- It removes itself.
once.
Why does bell.off("ring", () => console.log("ding")) not remove the listener added with the same text?Tap to reveal
- Each arrow function is a new function.
It is a different function: off needs the very same one.
node -e 'const E = require("events"); const e = new E(); e.once("x", () => console.log("hi")); e.emit("x"); console.log(e.emit("x"))'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
hi
false
- The first emit runs the once listener, which removes itself.
- The second emit finds no listener.
It prints hi, then false.
Did you know?
Events as a loop
Waiting for one event has a big brother: waiting for every one. The Node manual says events.on returns an async iterator of an event, so for await (const args of on(emitter, "ring")) runs once for each ring, with the arguments as an array. It throws if the emitter emits error, and removes its listeners when the loop is left.
Why it fits here: It answers this topic's question: events.on turns an event into a loop that for await can wait on, ring after ring.
Source: Node.js manual: Events
An event about listeners
An emitter even announces its own listeners. The Node manual says an EventEmitter emits its own newListener event before a listener is added to its list. Listeners for newListener receive the event's name and the listener being added. So a program can notice the first listener for an event, and start some work only when someone is listening.
Why it fits here: It adds to this topic's listeners: an emitter rings newListener whenever a listener is added.
Source: Node.js manual: Events
In one line
once runs a listener one time; prependListener puts one at the front; off removes the very same function; removeAllListeners clears an event; events.once gives a promise of the next emit.
The error event
At a glance
One event is different from all the others: error. It is how an emitter says that something went wrong.
If an emitter emits error and nobody listens for it, Node throws the error, and the program stops with a report. So listen for error on every emitter that can fail, such as a file stream, and decide there what to do. When your own emitter reports a failure, emit a real Error object, so that the listener gets a message and a stack.
Take a guess: Can an emitter catch an async listener's error for you?
One event name is special: error. Node's own emitters use it to report a failure, such as a file that cannot be read or a connection that broke.
The rule is this. If an emitter emits error and nobody listens for error, the emitter throws the error, and if nothing catches it, the program stops:
app.js
const EventEmitter = require("events");
const boiler = new EventEmitter();
boiler.emit("error", new Error("boiler burst"));
console.log("never printed");
Terminal: node app.js
echo "[$?]"
node:events:497
throw er; // Unhandled 'error' event
^
Error: boiler burst
at Object.<anonymous> (/home/asha/shop/app.js:3:22)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Emitted 'error' event at:
at Object.<anonymous> (/home/asha/shop/app.js:3:8)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Node.js v22.23.1
[1]
Read the report from the top. The place is inside Node, in its events module, where emit throws; Node's own comment there says Unhandled 'error' event.
Then come the error and its own stack: it was made on line 3, column 22. Then comes a part that only events add, Emitted 'error' event at: the stack of the emit itself, line 3, column 8. The last line of the program never ran.
Why so strict? An error event that nobody hears would be a failure that nobody sees. Node prefers to stop, loudly, so that the failure is found.
Listening for error
Add a listener for error, and an error event becomes news like any other. The listener gets the error object, and the program goes on:
app.js
const EventEmitter = require("events");
const boiler = new EventEmitter();
boiler.on("error", (err) => console.log("handled:", err.message));
boiler.emit("error", new Error("boiler burst"));
console.log("still running");
Terminal: node app.js
handled: boiler burst
still running
emit throws, so try can catch it
With no listener, the throw comes from the emit call itself, so try and catch around it can catch it. Here the error is a string, not an Error, and Node wraps it in an error of its own:
app.js
const EventEmitter = require("events");
const boiler = new EventEmitter();
try {
boiler.emit("error", "burst");
} catch (e) {
console.log(e.code);
console.log(e.message);
}
Terminal: node app.js
ERR_UNHANDLED_ERROR
Unhandled error. ('burst')
Always emit Error objects, made with new Error("..."). An Error carries its own stack, which the report above used to show where it was made.
A listener that throws
A listener is called from inside emit, so an error thrown by a listener comes out of the emit call. The listeners after it do not run:
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("ring", () => { throw new Error("listener broke"); });
bell.on("ring", () => console.log("second listener"));
try {
bell.emit("ring");
} catch (e) {
console.log("caught:", e.message);
}
Terminal: node app.js
caught: listener broke
| What happens | The result |
|---|---|
| error emitted, with an error listener | the listener gets the error; the program goes on |
| an Error emitted as error, with no listener | emit throws it; uncaught, the program stops |
| anything else emitted as error, with no listener | emit throws ERR_UNHANDLED_ERROR |
| a listener throws | emit throws it; the listeners after it do not run |
Worked example 3
The boiler's emitter reports a failure with error. Make the hall log a burst pipe and keep running, and check that the boiler's other events still work after it.
What we have: an emitter with a heat event, and a pipe that will burst
What we need: the burst logged, and the heat events before and after it heard
The plan: add an error listener and a heat listener first, then emit heat, error and heat again
app.js
const EventEmitter = require("events");
const boiler = new EventEmitter();
boiler.on("error", (err) => console.log("logged:", err.message));
boiler.on("heat", (t) => console.log("heat now", t));
boiler.emit("heat", 80);
boiler.emit("error", new Error("pipe burst"));
boiler.emit("heat", 85);
console.log("the hall runs on");
Terminal: node app.js
heat now 80
logged: pipe burst
heat now 85
the hall runs on
- The error listener was added before any emit, so the error event found it.
- After the error, the emitter works as before: the second heat event was heard.
- The program reached its last line.
The burst is logged, and the hall runs on.
Check: Four lines, in the order of the emits, and the last line of the program printed.
A path that fails: adding the error listener after the emit. The emit finds no listener, throws, and the program stops at that line, before the listener is ever added.
When you are stuck: The program stops with Unhandled 'error' event
Add emitter.on("error", ...) before anything can emit error.
Read the part Emitted 'error' event at. Its first line is where the emit happened.
Emit Error objects, not strings. new Error("...") carries its own stack.
Your turn
An emitter emits error, and nobody listens for error. What happens?Tap to reveal
- The rule of the error event.
emit throws the error; if nothing catches it, the program stops.
An emitter has an error listener, and emits error. Does the program stop?Tap to reveal
- The listener receives the error.
No. The listener handles it, and the program goes on.
node -e 'const E = require("events"); const e = new E(); e.on("error", (x) => console.log("got", x.message)); e.emit("error", new Error("leak"))'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
got leak
- There is an error listener.
- It receives the Error object and prints its message.
It prints got leak.
Did you know?
A switch for async listeners
An async listener that throws leaves a rejected promise that nobody handles. Node has a switch for that. Its manual calls async event handlers problematic for this reason, and offers the option captureRejections. An emitter made with new EventEmitter({ captureRejections: true }) catches such a rejection and routes the error to its error event, where a listener can deal with it.
Why it fits here: It answers this topic's question: with captureRejections, an emitter sends an async listener's error to its error event.
Source: Node.js manual: Events
Watching errors without catching them
Some code only wants to see errors, for a log, without handling them. The Node manual offers events.errorMonitor for that. A listener added with it is called before the regular error listeners, but changes nothing about what happens next: the program still crashes if no regular error listener is installed.
Why it fits here: It sharpens this topic's rule: an errorMonitor listener only watches, so a real error listener is still needed.
Source: Node.js manual: Events
In one line
An error event that nobody listens for is thrown, and stops the program. Listen for error on every emitter that can fail, and emit Error objects.
Emitters of your own
At a glance
Any object of yours can ring bells too. A class that extends EventEmitter gets emit, on and the rest for free.
Its constructor calls super() first, and then sets up its own data. Its methods do their work and announce the news with this.emit, such as a valve that emits open when it opens. Many of Node's own objects are built this way: process, every stream and every server are emitters that you already listen to. Listening to them is the same as listening to your own.
Take a guess: Does Node also offer the browser's way of handling events?
So far, each emitter was a bare EventEmitter. A real part of a program has its own data and methods, and it also has news to announce. A class that extends EventEmitter gets both: its own fields and methods, and on, once, off and emit.
app.js
const EventEmitter = require("events");
class Boiler extends EventEmitter {
constructor() {
super();
this.heat = 20;
}
warm(by) {
this.heat += by;
if (this.heat > 90) this.emit("hot", this.heat);
}
}
const b = new Boiler();
b.on("hot", (heat) => console.log("too hot:", heat));
b.warm(50);
b.warm(30);
console.log(b.heat, b instanceof EventEmitter);
Terminal: node app.js
too hot: 100
100 true
Three things to notice. The constructor calls super() first: a class that extends another must let the other set itself up before the constructor uses this.
The method warm announces its news with this.emit: inside a method, this is the boiler, which is an emitter. And a Boiler is an EventEmitter, as instanceof says.
The first warm, to 70, announced nothing. The second, to 100, rang hot, and the listener heard it. The code that uses the boiler decides what to do about the heat; the boiler only reports it.
What an emitter holds
console.log shows what is inside an emitter. The fields whose names start with an underscore are Node's own: read them to learn, and never change them.
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
console.log(bell);
bell.on("ring", () => {});
bell.once("stop", function stop() {});
console.log(bell);
Terminal: node app.js
EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(shapeMode)]: false,
[Symbol(kCapture)]: false
}
EventEmitter {
_events: [Object: null prototype] {
ring: [Function (anonymous)],
stop: [Function: bound onceWrapper] { listener: [Function: stop] }
},
_eventsCount: 2,
_maxListeners: undefined,
[Symbol(shapeMode)]: false,
[Symbol(kCapture)]: false
}
The field _events keeps the listeners by event name: one function alone, or an array when there are several. A once listener is kept wrapped in a function of Node's, called onceWrapper, which removes it after its first call. The field _eventsCount counts the event names.
Node's own emitters
Much of Node is built on EventEmitter. The object process is an emitter, and it announces the end of the program in two steps: beforeExit when the event loop has nothing left to do, then exit, with the exit code:
app.js
process.on("exit", (code) => console.log("exit event, code", code));
process.on("beforeExit", () => console.log("before exit"));
console.log("main done");
Terminal: node app.js
main done
before exit
exit event, code 0
Streams, the subject of the next two sections, are emitters too, and so are the servers of the next lesson:
app.js
const fs = require("fs");
const EventEmitter = require("events");
const stream = fs.createReadStream("app.js");
console.log(stream instanceof EventEmitter, typeof stream.on);
stream.destroy();
Terminal: node app.js
true function
Worked example 4
Make a Gauge class. Its read(value) method keeps every reading and announces reading each time, and alarm, with the gauge's name and the value, when the value passes the gauge's limit.
What we have: a limit for each gauge, and three readings for the boiler: 70, 85 and 95
What we need: an ALARM line for the reading above 90, and every reading kept
The plan: extend EventEmitter; keep name, limit and the readings in the constructor after super(); emit from read; listen for alarm
app.js
const EventEmitter = require("events");
class Gauge extends EventEmitter {
constructor(name, limit) {
super();
this.name = name;
this.limit = limit;
this.readings = [];
}
read(value) {
this.readings.push(value);
this.emit("reading", value);
if (value > this.limit) this.emit("alarm", this.name, value);
}
}
const boiler = new Gauge("boiler", 90);
boiler.on("alarm", (name, value) => console.log(`ALARM: ${name} at ${value}`));
for (const v of [70, 85, 95]) boiler.read(v);
console.log(boiler.readings, boiler.listenerCount("reading"));
Terminal: node app.js
ALARM: boiler at 95
[ 70, 85, 95 ] 0
- Each read keeps the value and announces reading, which nobody listens to here, so that emit returns false.
- Only 95 is above 90, so alarm rang once, with two arguments.
- listenerCount("reading") is 0: announcing an event that nobody hears is allowed.
One ALARM line, for 95, and all three readings kept.
Check: Of 70, 85 and 95, only 95 is above the limit of 90.
A path that fails: leaving out super() in the constructor. JavaScript then refuses this.name with a ReferenceError, as a class that extends another must call super before it uses this.
When you are stuck: this.emit is not a function
Check that the class says extends EventEmitter.
Check that the constructor calls super() before it uses this.
require("events") gives the class itself; const { EventEmitter } = require("events") gives the same class.
Your turn
What must the constructor of class Pump extends EventEmitter call before it uses this?Tap to reveal
- The class it extends sets itself up first.
super().
Name one of Node's own emitters.Tap to reveal
- Its exit event comes at the end of every program.
process, or any stream.
node -e 'const E = require("events"); class B extends E {} const b = new B(); b.on("x", () => console.log(b instanceof E)); b.emit("x")'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
true
- B extends E, so a B is an E.
- The listener prints instanceof's answer.
It prints true.
Did you know?
The browser's EventTarget, in Node
Node also speaks the browser's language of events. Its manual says Node has its own implementation of the EventTarget web API, with addEventListener, used by some of Node's core APIs. Since Node 15.0.0, EventTarget and Event are available everywhere as globals, so code written for the browser's events can often run in Node unchanged.
Why it fits here: It answers this topic's question: Node offers the browser's EventTarget as well as its own EventEmitter.
Before class there was util.inherits
Emitters of your own were once made without class. Older Node code used util.inherits to copy EventEmitter's methods onto a constructor function. Node's manual now says its use is discouraged, and asks for the ES6 class and extends keywords instead, adding that the two styles are semantically incompatible. So in old code, util.inherits is a sign of the older style.
Why it fits here: It dates this topic's class ... extends EventEmitter: older Node code used util.inherits, now discouraged.
Source: Node.js manual: Util
In one line
A class that extends EventEmitter, calling super() first, has its own data and methods and announces its news with this.emit; process, streams and servers are emitters too.
Streams: a file a piece at a time
At a glance
Reading a whole file at once is fine for a few lines. A log of many gigabytes would not fit in memory, so a stream hands it over a piece at a time.
A readable stream is an emitter. It emits data for each piece, called a chunk, then end when there is no more, then close. The option highWaterMark sets the size of a chunk, and an encoding makes the stream give whole characters. For whole lines, readline reads a stream line by line.
Take a guess: Did Node's streams always wait until someone asked for data?
Lesson 04 read whole files: readFileSync and readFile hand over a file all at once. For a ledger of a few lines, that is right. A log of many gigabytes would not fit in the computer's memory, and a program that looks at one line at a time never needs the whole file at once.
A stream hands you data a piece at a time. A readable stream is an emitter: it emits data for each piece, called a chunk, and end when there is no more.
app.js
const fs = require("fs");
const stream = fs.createReadStream("readings.txt", { encoding: "utf8", highWaterMark: 10 });
stream.on("data", (chunk) => console.log("chunk:", JSON.stringify(chunk)));
stream.on("end", () => console.log("end"));
stream.on("close", () => console.log("close"));
console.log("stream made");
Terminal: node app.js
stream made
chunk: "boiler 95\n"
chunk: "pump 40\npr"
chunk: "ess 70\n"
end
close
fs.createReadStream gives back the stream at once, before any reading, which is why stream made printed first. The chunks come later, one by one, from the event loop.
The option highWaterMark sets the size of each chunk, here 10 bytes; without it, a file stream reads 65,536 bytes at a time. A chunk ends where its size ends, even in the middle of a line, as pump 40 and press show.
After the last chunk, end says that no data is left, and close says that the file has been closed. The encoding option makes each chunk a string, as it did for readFileSync.
Chunks are bytes
Without an encoding, each chunk is a Buffer. This small file fits in one chunk of the usual size:
app.js
const fs = require("fs");
const stream = fs.createReadStream("readings.txt");
stream.on("data", (chunk) => console.log(chunk));
stream.on("end", () => console.log("end"));
Terminal: node app.js
<Buffer 62 6f 69 6c 65 72 20 39 35 0a 70 75 6d 70 20 34 30 0a 70 72 65 73 73 20 37 30 0a>
end
A character cut in two
Lesson 04 showed that the rupee sign takes three bytes. A chunk of 2 bytes must cut it in two. With an encoding, the stream keeps the first two bytes back until the third arrives, so no chunk ever holds half a character:
app.js
const fs = require("fs");
const stream = fs.createReadStream("price.txt", { encoding: "utf8", highWaterMark: 2 });
stream.on("data", (chunk) => console.log(JSON.stringify(chunk)));
Terminal: node app.js
"₹4"
"0 "
"pu"
"mp"
"\n"
The first chunk, two bytes of the rupee sign, gave no string at all. With the third byte, the second chunk gave the whole sign and the 4 after it.
Chunks in a loop: for await
A readable stream also works with for await, which you met with promises: each turn of the loop waits for the next chunk.
app.mjs
import { createReadStream } from "node:fs";
let n = 0;
for await (const chunk of createReadStream("readings.txt", { highWaterMark: 10 })) {
n++;
console.log(n, chunk.length, chunk);
}
console.log("chunks:", n);
Terminal: node app.mjs
1 10 <Buffer 62 6f 69 6c 65 72 20 39 35 0a>
2 10 <Buffer 70 75 6d 70 20 34 30 0a 70 72>
3 7 <Buffer 65 73 73 20 37 30 0a>
chunks: 3
Line by line: readline
Most text is used line by line. The built-in module readline reads a stream and emits line for each whole line, however the chunks were cut, then close at the end:
app.js
const fs = require("fs");
const readline = require("readline");
const rl = readline.createInterface({ input: fs.createReadStream("readings.txt") });
let total = 0;
rl.on("line", (line) => { total += Number(line.split(" ")[1]); });
rl.on("close", () => console.log("total", total));
Terminal: node app.js
total 205
The same interface works with for await, one line for each turn of the loop:
app.mjs
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
const rl = createInterface({ input: createReadStream("readings.txt"), crlfDelay: Infinity });
for await (const line of rl) console.log(line.toUpperCase());
console.log("all lines read");
Terminal: node app.mjs
BOILER 95
PUMP 40
PRESS 70
all lines read
The option crlfDelay: Infinity, which Node's documentation uses in its own example, makes a line end of \r\n, written by Windows programs, count as one line end.
| Event or option | What it means |
|---|---|
data | a chunk has arrived: a Buffer, or a string with an encoding |
end | no data is left |
close | the file has been closed |
error | reading failed, such as ENOENT for a missing file |
highWaterMark | the size of each chunk, in bytes |
encoding | chunks as strings, never cutting a character |
Worked example 5
Count the lines and bytes of a log without holding it all at once: count the newline bytes in each chunk as it arrives.
What we have: readings.txt, read in chunks of 8 bytes
What we need: the number of lines and of bytes
The plan: add each chunk's length to bytes; count each byte 10, the newline, in lines; print both at end
app.js
const fs = require("fs");
let lines = 0;
let bytes = 0;
const stream = fs.createReadStream("readings.txt", { highWaterMark: 8 });
stream.on("data", (chunk) => {
bytes += chunk.length;
for (const b of chunk) if (b === 10) lines += 1;
});
stream.on("end", () => console.log(lines, "lines,", bytes, "bytes"));
Terminal: node app.js
3 lines, 27 bytes
- Each chunk is a Buffer, and a for of loop over a Buffer gives its bytes, one number at a time.
- A newline is the byte 10, so counting tens counts lines, wherever a chunk was cut.
- Only one chunk is held at a time, so the same program works for a file of any size.
3 lines, 27 bytes.
Check: Lesson 04 counted the same file: 27 bytes, three lines, each ending with a newline.
A path that fails: counting with chunk.toString().split("\n").length for each chunk. Each chunk then adds one too many, and a line cut between two chunks is counted twice.
When you are stuck: The data comes in odd pieces
Chunks are cut by size, not by line. Join them, or use readline for whole lines.
Give an encoding, or call stream.setEncoding("utf8"), to get strings that never cut a character in two.
Code after createReadStream runs first. The data comes later, from the event loop.
Your turn
Which event says that a readable stream has no data left?Tap to reveal
- It comes after the last chunk, before close.
end.
What does highWaterMark set for a file stream?Tap to reveal
- The last example used 8.
The size of each chunk, in bytes.
node -e 'const s = require("fs").createReadStream("readings.txt", { highWaterMark: 20 }); let n = 0; s.on("data", () => n++); s.on("end", () => console.log(n))'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2
- The file has 27 bytes.
- Chunks of 20 bytes: one of 20, then one of 7.
It prints 2.
Did you know?
Streams once poured at once
Node's streams were not always this patient. Its manual says that before Node 0.10, data events began at once, instead of waiting to be asked, so a program that needed time to decide what to do had to store the data or lose it. Today every readable stream begins paused, and starts to flow when asked, for example when a data listener is added.
Why it fits here: It answers this topic's question: before Node 0.10 data poured out at once, while today a stream waits until something asks.
Source: Node.js manual: Stream (Compatibility with older Node.js versions)
readline also listens to people
readline is not only for files. Its manual says it reads any readable stream one line at a time, such as process.stdin, where typed input arrives. In a terminal it keeps a history of up to 30 typed lines by default, and Ctrl+P brings back the previous one. Given a completer function, it also completes a word when Tab is pressed.
Why it fits here: It widens this topic's readline: besides a file's lines, it serves people typing, with a history and Tab completion.
Source: Node.js manual: Readline
In one line
A readable stream emits data for each chunk, then end, then close; highWaterMark sets a chunk's size, an encoding gives whole characters, and readline gives whole lines.
Writing streams and pipes
At a glance
A writable stream is the other end of the pipe: it takes chunks and sends them on, into a file or onto the screen. Each chunk is written in the order it was given.
write gives a writable stream one chunk, and end gives the last chunk and closes it. When everything has been written, the stream emits finish. The method pipe copies a readable stream into a writable one and ends it when the reading ends. Streams report failure with the error event, like any emitter.
Take a guess: If the reading side fails, does pipe close the writing side for you?
A writable stream takes data a piece at a time and writes it on. fs.createWriteStream makes one that writes into a file.
Its method write adds a chunk. Its method end adds a last chunk, if you give one, and says that no more will come.
app.js
const fs = require("fs");
const out = fs.createWriteStream("log.txt");
out.write("engine started\n");
out.write("boiler hot\n");
out.end("pump low\n");
out.on("finish", () => console.log("all written"));
console.log("asked to write");
Terminal: node app.js
cat log.txt
asked to write
all written
engine started
boiler hot
pump low
The calls to write and end return at once; the writing itself happens later, from the event loop, which is why asked to write printed first. The finish event says that every chunk has been written.
Read the file only after finish. Here cat ran after the program had ended, so the file was complete.
The order of a write stream's events
A write stream announces each step: open and ready when its file is open, finish when all is written, and close when the file is closed. The callback given to end runs just before finish:
app.js
const fs = require("fs");
const out = fs.createWriteStream("log.txt");
console.log(out.write("engine started\n"));
out.end("pump low\n", () => console.log("end callback"));
out.on("finish", () => console.log("finish"));
out.on("close", () => console.log("close"));
out.on("open", () => console.log("open"));
out.on("ready", () => console.log("ready"));
Terminal: node app.js
cat log.txt
true
open
ready
end callback
finish
close
engine started
pump low
The first line, true, is the answer of write. True means that the stream has room for more. False would mean that its waiting chunks have reached its limit: a careful writer then waits for the drain event before writing more.
pipe: one stream into another
Reading from one stream and writing into another is so common that readable streams have a method for it. readable.pipe(writable) writes each chunk it reads into the writable, waits when the writable is full, and ends the writable when the readable ends:
app.js
const fs = require("fs");
fs.createReadStream("readings.txt").pipe(fs.createWriteStream("copy.txt")).on("finish", () => console.log("copied"));
Terminal: node app.js
cat copy.txt
copied
boiler 95
pump 40
press 70
The method pipe gives back the writable, so on can follow it at once. A file of any size is copied this way, one chunk at a time.
The terminal is a stream too. process.stdout is a writable stream, so a file can be piped straight into it. The method pipe never ends process.stdout, as the program may still want to print:
app.js
const fs = require("fs");
fs.createReadStream("readings.txt").pipe(process.stdout);
Terminal: node app.js
boiler 95
pump 40
press 70
When a stream fails
Streams report failure with the error event, so the error event's rule holds for them. With a listener, the failure is news; after it, the stream closes:
app.js
const fs = require("fs");
const stream = fs.createReadStream("nosuch.txt");
stream.on("error", (err) => console.log("error:", err.code));
stream.on("close", () => console.log("close"));
Terminal: node app.js
error: ENOENT
close
Without a listener, the stream's error stops the program. The report says that the event was emitted on a ReadStream, from inside Node's own stream code:
app.js
const fs = require("fs");
fs.createReadStream("nosuch.txt");
Terminal: node app.js
echo "[$?]"
node:events:497
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open 'nosuch.txt'
Emitted 'error' event on ReadStream instance at:
at emitErrorNT (node:internal/streams/destroy:170:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at process.processTicksAndRejections (node:internal/process/task_queues:89:21) {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'nosuch.txt'
}
Node.js v22.23.1
[1]
| Method or event | What it does |
|---|---|
writable.write(chunk) | adds a chunk; true while there is room for more |
writable.end(chunk) | adds a last chunk, if given, and says no more will come |
finish | every chunk has been written |
close | the file has been closed |
readable.pipe(writable) | writes every chunk into writable, then ends it |
error | the stream failed; listen for it on every stream |
Worked example 6
Write the names of the hot gauges into hot.txt with streams: read readings.txt line by line, write each hot name, and say done when all is written.
What we have: readings.txt, three lines, read through readline
What we need: hot.txt with boiler and press, and done printed once everything is written
The plan: make a reader of lines and a write stream; write each hot name; end the write stream when the lines are over; print done at finish
app.js
const fs = require("fs");
const readline = require("readline");
const rl = readline.createInterface({ input: fs.createReadStream("readings.txt") });
const out = fs.createWriteStream("hot.txt");
rl.on("line", (line) => {
const [name, value] = line.split(" ");
if (Number(value) > 60) out.write(name + "\n");
});
rl.on("close", () => out.end());
out.on("finish", () => console.log("done"));
Terminal: node app.js
cat hot.txt
done
boiler
press
- The line listener writes one name for each reading above 60.
- When readline closes, every line has been seen, so it is time for end.
- done waits for finish, which comes only after both names are in the file.
hot.txt holds boiler and press, and done printed once.
Check: The same two names that lesson 04 found, this time with only one chunk of the file held at a time.
A path that fails: calling out.end() straight after making the streams. The writable is ended before any line arrives, and Node's documentation says that a write after end raises an error.
When you are stuck: A written file is empty or cut short
Read the file only after finish: the writing happens later.
Call end once, after the last write.
Listen for error on every stream. A missing folder makes a write stream fail.
Your turn
Which event of a writable stream says that every chunk has been written?Tap to reveal
- It comes after end, before close.
finish.
What does readable.pipe(writable) do when the readable ends?Tap to reveal
- The copy example's finish came from it.
It ends the writable.
node -e 'require("fs").createReadStream("readings.txt").pipe(process.stdout)'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
boiler 95
pump 40
press 70
- The file's chunks are written into the terminal's stream.
- So the terminal shows the file.
It prints the three lines of readings.txt.
Did you know?
pipe leaves a mess on errors
pipe has a weak spot. The Node manual warns that if the readable stream emits an error during processing, the writable destination is not closed automatically, so each stream must be closed by hand to prevent memory leaks. Its answer is stream.pipeline, which pipes between streams while forwarding errors, cleaning up properly and calling back when the pipeline is complete.
Why it fits here: It answers this topic's question: pipe does not close the writer when the reader fails, while stream.pipeline cleans up both.
Source: Node.js manual: Stream
Streams of objects
A stream can carry more than bytes. Node's manual says the streams made by Node's own APIs carry only strings and binary data, such as buffers, while a stream made with the objectMode option can carry other JavaScript values. The one value it cannot carry is null, which a stream uses to signal its end. In object mode, highWaterMark counts objects, not bytes.
Why it fits here: It widens this topic's chunks: a stream made with objectMode takes any value but null, and its highWaterMark counts objects.
In one line
A writable stream takes chunks with write and a last one with end, and emits finish when all is written; pipe copies a readable into a writable and ends it; streams report failure with the error event.
Where it is used
Events and streams are everywhere in Node. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| emitters and listeners | parts that tell others what happened | a web server, which emits request for every visitor |
| once and events.once | waiting for one moment | a program that waits until its server is listening |
| the error event | failures that must not go unseen | a database connection that drops |
| classes that extend EventEmitter | your own parts with news | a game's player, which announces each new score |
| readable streams | large files and network data | a log of many gigabytes, read one line at a time |
| writable streams and pipe | copying and sending data | a server sending a large file to a browser, chunk by chunk |
The Foreman's bells are events, the brass bell on each part is an emitter, and the people who sign up to hear a bell are listeners. The note on the rope is emit's arguments, the alarm that nobody may leave unanswered is the error event, and the small bell for each page of a ledger is a stream's data event.
Mistakes and debugging
These are the slips that people meet most often with events and streams. Every output below is the real one, from the code shown.
1. Listening after the event
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.emit("ring");
bell.on("ring", () => console.log("heard it"));
console.log("done");
Terminal: node app.js
done
The emit ran its listeners at once, and there were none yet. The fix: add listeners before anything can emit.
2. Two names that differ
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("Ring", () => console.log("heard it"));
console.log(bell.emit("ring"));
Terminal: node app.js
false
Event names are exact: Ring and ring are two events. The fix: one spelling, kept in one place, such as a constant.
3. Reading a file before the stream has written it
app.js
const fs = require("fs");
const out = fs.createWriteStream("log.txt");
out.end("engine started\n");
console.log("right away:", fs.existsSync("log.txt"));
out.on("finish", () => console.log("after finish:", JSON.stringify(fs.readFileSync("log.txt", "utf8"))));
Terminal: node app.js
right away: false
after finish: "engine started\n"
The stream had not even opened its file when the next line ran. The fix: use the file inside the finish listener.
4. Turning each chunk into text on its own
app.js
const fs = require("fs");
let text = "";
fs.createReadStream("price.txt", { highWaterMark: 2 })
.on("data", (chunk) => { text += chunk.toString(); })
.on("end", () => console.log(text.trim()));
Terminal: node app.js
��40 pump
The rupee sign was cut between two chunks, and each half became a sign for a broken character. The fix: give the stream an encoding, or call setEncoding("utf8"), so that it joins the halves before it gives you text.
5. An async listener that throws
app.js
const EventEmitter = require("events");
const bell = new EventEmitter();
bell.on("ring", async () => { throw new Error("async listener broke"); });
bell.emit("ring");
console.log("emit returned");
Terminal: node app.js
echo "[$?]"
emit returned
/home/asha/shop/app.js:3
bell.on("ring", async () => { throw new Error("async listener broke"); });
^
Error: async listener broke
at EventEmitter.<anonymous> (/home/asha/shop/app.js:3:37)
at EventEmitter.emit (node:events:519:28)
at Object.<anonymous> (/home/asha/shop/app.js:4:6)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Node.js v22.23.1
[1]
An async function gives back a promise, and emit does not look at what its listeners give back. The error became a rejected promise that nobody handled, and Node stopped after the main code. The fix: put try and catch inside an async listener.
The debugging corner: who is listening?
emitter.eventNames() lists the events that have listeners, emitter.listenerCount(name) counts them, and console.log(emitter) shows them all in its _events field. When an event seems to vanish, these three answer whether anyone was listening.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
app.js
const EventEmitter = require("events");
class Pump extends EventEmitter {
start() { this.emit("started", "pump 2"); }
}
const pump = new Pump();
pump.on("started", (name) => console.log(name, "started")); // every time
pump.once("started", () => console.log("first start")); // one time only
pump.on("error", (err) => console.log("pump error:", err.message)); // always handle error
pump.start();
pump.start();
pump.emit("error", new Error("no water"));
Terminal: node app.js
pump 2 started
first start
pump 2 started
pump error: no water
| When you see | It means | Do |
|---|---|---|
Unhandled 'error' event | an error event with no listener | add emitter.on("error", ...) |
ERR_UNHANDLED_ERROR | something that is not an Error was emitted as error, unheard | emit new Error(...), and listen for error |
emit gives false | nobody listens to that name | check the spelling; add listeners first |
| off removes nothing | a different function was given | keep the listener in a name |
| chunks cut in odd places | chunks are cut by size | readline for lines, an encoding for characters |
| a file empty right after writing | the writing happens later | wait for finish |
The story: A hall of bells
You hang a bell on every part that has news. Each part rings its own bell, with a note on the rope that says what happened. Whoever cares signs up to listen, for every ring or only the next one, and leaves when they are done. An alarm bell that nobody answers stops the whole hall, so somebody always answers it.
Long jobs ring small bells too. A ledger is read a page at a time, and a page bell rings for each one, so the work never waits for the whole book.
The Foreman listens to the hall ringing and smiles. "Next," she says, "we open the great doors, and answer the city."
Reagents gathered: event, EventEmitter, listener, emit, error event, stream.
Sources
- The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)