Explain stream in Node.js along with its various types.

Streams are pipes that let you easily read data from a source and pipe it to a destination. Simply put, a stream is nothing but an EventEmitter and implements some specials methods. Depending on the methods implemented, a stream becomes Readable, Writable, or Duplex (both readable and writable).

For example, if we want to read data from a file, the best way to do it from a stream is to listen to data event and attach a callback. When a chunk of data is available, the readable stream emits a data event and your callback executes. Take a look at the following snippet:

Image for post

Types of streams are: Readable, Writable, Duplex and Transform.


Streams in Node.js are the collection of data similar to arrays and strings. They are objects using which you can read data from a source or write data to a destination in a continuous manner. It might not be available at once and need not to have fit in the memory. These streams are especially useful for reading and processing a large set of data. In Node.js, there are four fundamental types of streams:

  1. Readable: Used for reading large chunks of data from the source.
  2. Writeable: Use for writing large chunks of data to the destination.
  3. Duplex: Used for both the functions; read and write.
  4. Transform: It is a duplex stream that is used for modifying the data.

Comments

Popular posts from this blog

Which node logger did you use in your project?

What is a Callback function in Node.js?