What is readable.wrap() in the Node.js Stream Module?
readable.wrap(stream)
Previous Node.js versions do not fully support all the Stream Module methods defined in the current Stream Module from Node.js 0.10. So, for convenience and backward compatibility purposes, the readable.wrap() method reads old Node.js readable streams from old legacy Node.js applications.
readable.wrap() creates a readable stream that uses old Node.js readable streams as its data source, which is passed as the argument to the function.
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
const { OldReader } = require('./old-api-module.js');const { Readable } = require('stream');const oldReader = new OldReader();const newReader = new Readable().wrap(oldReader);newReader.on('readable', () => {newReader.read(); // etc.});
Explanation
In the above example, oldReader is the old Node.js readable stream, which is used as the data source for newReader readable stream by using the readable.resume() method. This allows the new functionalities in the Stream Module to be available to use on the old readable stream. Visit the official documentation for more information.
Free Resources