Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js

What is readable.read() in the Node.js Stream Module?

Abdul Monum

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

readable.read([size])

The readable.read() method in the Node.js Stream Module is used to read data from the internal Buffer when the readable stream is in paused mode.

By default, readable.read() returns the data in a Buffer object. When the readable stream is in flowing mode, readable.read() is automatically called until the data elements from the stream are fully consumed.

Arguments

size: Optional parameter that specifies how much data is to be read in bytes. Must be of <Number> data type and less than or equal to 1 GiB.

If size is not specified, then all of the data from the internal buffer is returned.

Return value

By default, Buffer object is returned unless the stream is in object mode or an encoding is specified using the readable.setEncoding() method. Other return values are the following:

  • String
  • Null
  • Any type

If complete size bytes are not present in the internal Buffer, then Null is returned. However, if the stream has ended, then all of the remaining data in the internal buffer is returned. If there is no data left in the internal buffer, then Null is returned.

Stream Module in Node.js provides the API for handling the sequence of data flowing over time. The stream types supported in the Node.js Stream Module are:

  • Writable: The stream to which data is written.
  • Readable: The stream from which data is read.
  • Duplex: The stream that is both Readable and Writable.
  • Transform: The stream that is Duplex but can change or transform data as it is read or written.

All of these streams are implemented as classes in the Stream Module. For example, Readable streams follow the interface defined by stream.Readable class. The readable.resume() method is defined in the stream.Readable class.

Readable streams

Readable streams run in two modes: flowing or paused.

  • Flowing mode: Data elements are read from the system asynchronously and provided to the application interface as soon as possible using the Event Emitter interface in Node.js.
  • Paused mode: stream.read() must be called explicitly to read the data elements from the stream.

The following are a few examples of Readable streams:

  • HTTP requests and responses
  • fs read streams
  • TCP sockets
  • zlib streams
  • process.stdin

Example

index.js
example.txt
let fs = require("fs");
const readable = fs.createReadStream('example.txt');
let chunks = [];
readable.on('readable', () => {
let chunk;
console.log('Stream is now readable');
while (null !== (chunk = readable.read(8))) {
console.log(`Chunk read: ${chunk}`)
chunks.push(chunk)
}
console.log(`Null returned`)
});
readable.on('end', () => {
const file_content = chunks.join('')
console.log('Reached end of stream.');
console.log(`File content: ${file_content}`)
});

Explanation

  • In the above code, we first create a readable stream that uses data from example.txt, which contains the string “How to use readable.read()”.

  • Next, we use the readable.on('readable') handler, which allows fine-grained control over the transfer of data. Since our internal buffer contains our readable stream data, the program proceeds inside readable.on('readable') and prints “Stream is now readable”.

  • We use a while loop to consume data in chunks of 8 bytes from the internal buffer, using the readable.read() method. The program prints each chunk and stores them in the array chunks.

  • readable.read() returns Null when 8 bytes are not available to read, and the while loop terminates. At this moment, the stream has ended. However, since the string “()” remains in the internal buffer, the readable.on('readable') handler is fired again and the readable.read() reads the remaining string in the internal buffer.

  • Finally, since there is no more data available, the readable.on('end') handler is fired, which concatenates all chunks from the array chunks and displays the whole file content.

RELATED TAGS

node.js

CONTRIBUTOR

Abdul Monum
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring