Getting Started with Streams

Learn about base classes that make up streams in Node.js.

We'll cover the following

We’ve learned why streams are so powerful, but also that they’re everywhere in Node.js, starting from its core modules. For example, we’ve 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, the zlib module allows us to compress and decompress data using a streaming interface and, finally, even the crypto module exposes some useful streaming primitives like createCipheriv and createDecipheriv.

Now that we know why streams are so important, let’s 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:

  • Readable

  • Writable

  • Duplex

  • 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, finish when a Writable stream has completed writing, or error when something goes wrong.

One reason why streams are so flexible is the fact that they can handle not just binary data, but almost any JavaScript value. In fact, they support two operating modes:

  • Binary mode: To stream data in the form of chunks, such as buffers or strings

  • Object mode: To stream data as a sequence of discrete objects (allowing us to use almost any JavaScript value)

Get hands-on with 1200+ tech skills courses.