What is readable.read() in the Node.js Stream Module?
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 bothReadableandWritable.Transform: The stream that isDuplexbut 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
fsread streams- TCP sockets
- zlib streams
process.stdin
Example
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
readablestream that uses data fromexample.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 ourreadablestream data, the program proceeds insidereadable.on('readable')and prints “Stream is now readable”. -
We use a
whileloop to consume data in chunks of 8 bytes from the internal buffer, using thereadable.read()method. The program prints each chunk and stores them in the arraychunks. -
readable.read()returnsNullwhen 8 bytes are not available to read, and thewhileloop terminates. At this moment, the stream has ended. However, since the string “()” remains in the internal buffer, thereadable.on('readable')handler is fired again and thereadable.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 arraychunksand displays the whole file content.
Free Resources