Skip to content

Commit

Permalink
doc: define more cases for stream event emissions
Browse files Browse the repository at this point in the history
PR-URL: #53317
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
avivkeller authored and marco-ippolito committed Jul 19, 2024
1 parent 9f95d41 commit 55ac53c
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions doc/api/stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -1278,9 +1278,11 @@ changes:
-->

The `'readable'` event is emitted when there is data available to be read from
the stream or when the end of the stream has been reached. Effectively, the
`'readable'` event indicates that the stream has new information. If data is
available, [`stream.read()`][stream-read] will return that data.
the stream, up to the configured high water mark (`state.highWaterMark`). Effectively,
it indicates that the stream has new information within the buffer. If data is available
within this buffer, [`stream.read()`][stream-read] can be called to retrieve that data.
Additionally, the `'readable'` event may also be emitted when the end of the stream has been
reached.

```js
const readable = getReadableStreamSomehow();
Expand Down Expand Up @@ -1549,13 +1551,14 @@ readable.on('end', () => {
});
```

Each call to `readable.read()` returns a chunk of data, or `null`. The chunks
are not concatenated. A `while` loop is necessary to consume all data
currently in the buffer. When reading a large file `.read()` may return `null`,
having consumed all buffered content so far, but there is still more data to
come not yet buffered. In this case a new `'readable'` event will be emitted
when there is more data in the buffer. Finally the `'end'` event will be
emitted when there is no more data to come.
Each call to `readable.read()` returns a chunk of data or `null`, signifying
that there's no more data to read at that moment. These chunks aren't automatically
concatenated. Because a single `read()` call does not return all the data, using
a while loop may be necessary to continuously read chunks until all data is retrieved.
When reading a large file, `.read()` might return `null` temporarily, indicating
that it has consumed all buffered content but there may be more data yet to be
buffered. In such cases, a new `'readable'` event is emitted once there's more
data in the buffer, and the `'end'` event signifies the end of data transmission.

Therefore to read a file's whole contents from a `readable`, it is necessary
to collect chunks across multiple `'readable'` events:
Expand Down

0 comments on commit 55ac53c

Please sign in to comment.