m0meni
m0meni

Reputation: 16445

What does the _read function for readable streams do in nodejs?

I'm reading the docs and there's this description, but I don't understand what it means.

All Readable stream implementations must provide a _read method to fetch data from the underlying resource.

This method is prefixed with an underscore because it is internal to the class that defines it, and should not be called directly by user programs. However, you are expected to override this method in your own extension classes.

When data is available, put it into the read queue by calling readable.push(chunk). If push returns false, then you should stop reading. When _read is called again, you should start pushing more data.

What is the underlying resource? When would you actually specify a _read function, meaning what purpose does it serve?

Upvotes: 3

Views: 1929

Answers (1)

mscdex
mscdex

Reputation: 106736

The _read() function is used to notify the Readable stream that the highWaterMark has not been reached and that the stream can feel free to read more data from the underlying resource. The argument passed to _read() is a suggestion of the number of bytes (or number of items in the case of objectMode) to read from the underlying resource.

The underlying resource mentioned in the documentation is referring to any data source. It could be anything, including another Readable stream or it could be data that you generate dynamically (for example, a Readable stream that provides random binary data).

Upvotes: 7

Related Questions