Streams in Node.js
What is stream?
Streams are the collection of data like array or strings but the difference is that the all streams might not be available at a once and they don’t have to fit in memory. Stream is very useful to work with large amount of data and the data’s that’s come from the external source. They also give us power of composability in code.
Streams are also objects that we read data from a source or write data to a destination in continuous fashion.
The advantage of stream is given bellow-
- Memory efficiency: No need to carry the massive amounts of data in memory before process it.
- Time efficiency: It takes way less time to start processing the data as soon as you have it, rather than waiting till the whole data payload is available to start the process.
Types of streams:
There are four types of streams. They are-
- Writable streams
- Readable streams
We are going to describe about writable stream and readable stream.
Writable streams: Writable streams are the streams which data can be written. Writable object has a write() method which pass string or buffer to write something to the stream. And also a end() method that close the stream and give value in time of closing.
We can create a writable stream using createWriteStream() method. The example is given bellow-
Readable Stream: Readable stream is read data from source. The source can be simple file in file system, a buffer in memory, or even another stream.
creteReadStream() method is used to create a file readable from fs. Example is given bellow-
We can also read file using readFile() method.
Difference between writable Stream and Readable stream-
Screenshot captured from my Pluralsight course — Advanced Node.js