Getting started with streams
In the previous section, we learned why streams are so powerful, but also that they are everywhere in Node.js, starting from its core modules. For example, we have seen that the fs
module has createReadStream()
for reading from a file and createWriteStream()
for writing to a file, the http
request and response objects are essentially streams, and the zlib
module allows us to compress and decompress data using a streaming interface.
Now that we know why streams are so important, let's take a step back and start to explore them in more detail.
Anatomy of streams
Every stream in Node.js is an implementation of one of the four base abstract classes available in the stream
core module:
stream.Readable
stream.Writable
stream.Duplex
stream.Transform
Each stream
class is also an instance of EventEmitter
. Streams, in fact, can produce several types of events, such as end
, when a Readable
stream has finished reading, or error
, when something goes wrong.
Note
Please note...