Implementing Readable Streams
Explore how to implement custom Readable streams in Node.js by extending the Readable class and defining the internal _read method. Understand how to generate random string data, manage stream encoding, handle backpressure with push(), and properly signal the end of the stream. This lesson guides you through building and using a random data stream for efficient asynchronous data handling.
We'll cover the following...
Now that we know how to read from a stream, the next step is to learn how to implement a new custom Readable stream.
Custom readable stream
To do this, it’s necessary to create a new class by inheriting the prototype Readable from the stream module. The concrete stream should provide an implementation of the _read() method, which has the following signature.
readable._read(size)
The internals of the Readable class will call the _read() method, which in turn, will start to fill the internal buffer using the push() method.
readable.push(chunk)
Note: Please note that
read()is a method called by the stream consumers, while_read()is a method to be implemented by a stream subclass and should never be called directly. The underscore usually ...