In this tutorial, we will learn about readable streams in Node.js. Streams are a fundamental concept that powers Node.js applications.

Streams provide an efficient way to handle reading and writing files, network communications, and end-to-end information exchange. Unlike traditional methods, streams read chunks of data piece by piece, processing its content without loading it all into memory.

This makes streams particularly powerful when working with large amounts of data. There are four types of streams in Node.js:

  • Writable: streams to which we can write data.
  • Readable: streams from which data can be read.
  • Duplex: streams that are both readable and writable.
  • Transform: streams that can modify or transform data as it is written and read.

Creating a Readable Stream

Let's create a readable stream. First, go to the project and open the index.js file. Require the http and fs packages:


var http = require('http');
var fs = require('fs');

Next, create a text file inside the project. Name it message.txt and add some paragraphs. You can generate sample text from a lorem ipsum generator.

Now, create a read stream in the index.js file:


var readStream = fs.createReadStream(__dirname + 'message.txt');
readStream.on('data',function(chunk){
    console.log('new chunk recieved:');
    console.log(chunk);
});

Run the code by going to the command prompt and running the command:


node index.js

You will see the records in chunks. To display the actual text, add an encoder (utf8):


var readStream = fs.createReadStream(__dirname + 'message.txt','utf8');
readStream.on('data',function(chunk){
    console.log('new chunk recieved:');
    console.log(chunk);
});

Re-run the index.js file in the command prompt. You will see the text displayed.

In this way, you can use readable streams to efficiently handle data in your Node.js applications.