Events and streams
Much of Node is built on two ideas: events ("something happened, tell everyone who's interested") and streams ("process data piece by piece as it flows"). HTTP servers, file reads, sockets and child processes all use them.
EventEmitter
An EventEmitter lets one part of a program announce events and other parts react, without knowing about each other:
| Method | Does |
|---|---|
on(event, fn) |
Listen every time (alias addListener) |
once(event, fn) |
Listen only the next time |
emit(event, ...args) |
Call every listener, in order, synchronously |
off(event, fn) |
Stop listening (alias removeListener) |
Your own emitters
Classes often extend EventEmitter to expose events:
The special error event
If an emitter emits 'error' and nobody listens, Node throws it and the program crashes. Always listen for errors on emitters and streams:
Waiting for one event with await
events.once returns a promise for the next occurrence of an event:
Streams
A stream is a sequence of data that arrives (or leaves) a chunk at a time. Instead of loading a 2 GB video into memory, you handle a few kilobytes at a time.
| Type | Examples | You… |
|---|---|---|
| Readable | fs.createReadStream, an HTTP request body, process.stdin |
read from it |
| Writable | fs.createWriteStream, an HTTP response, process.stdout |
write to it |
| Duplex | A network socket | both |
| Transform | gzip compression, encryption, CSV parsing | write in, read changed data out |
Reading a stream
Readable streams are async iterables, so for await reads them chunk by chunk:
Writing a stream
Connecting streams with pipeline
The real power of streams is piping them together: data flows from a source, through transforms, into a destination, with memory use staying low. pipeline connects them and handles errors and clean-up:
On a real server you'd use the same pattern to compress a log file (zlib.createGzip()), stream a big file download to a user, or import a huge CSV into a database.
Backpressure
What if you read from a fast disk and write to a slow network? The writable stream's buffer fills up, write() returns false, and a well-behaved source pauses until the 'drain' event. This is called backpressure, and pipeline (and .pipe()) handle it for you automatically. That's the main reason to prefer pipeline over writing chunks by hand.
Streams from your own data
Readable.from turns any array or async generator into a stream:
Practice
- Create a
Timerclass that extends EventEmitter and emits'tick'every 100 ms and'end'after five ticks. - Write a Transform stream that numbers each line (
1: asha,2: rahul, …) and use it in apipelinefrom one file to another. - Use
readlinewithcreateReadStreamto find the longest line of a text file.
1.What happens if an EventEmitter emits 'error' and nobody is listening?
2.Why use streams for a 5 GB file?
3.What does pipeline handle for you?