Skip to content

Commit 78c1867

Browse files
doc: added example for Readable stream back-pressure (#5066)Co-authored-by: Claudio Wunder <[email protected]>
* added example for back-pressure Signed-off-by: Rishabh Bhandari <[email protected]> * linting fixes Signed-off-by: Rishabh Bhandari <[email protected]> --------- Signed-off-by: Rishabh Bhandari <[email protected]> Co-authored-by: Claudio Wunder <[email protected]>
1 parent 903c1c6 commit 78c1867

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

locale/en/docs/guides/backpressuring-in-streams.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,38 @@ readable.on('data', (data) =>
504504
);
505505
```
506506

507+
Here's an example of using [`.push()`][] with a Readable stream.
508+
509+
```javascript
510+
const { Readable } = require('stream');
511+
512+
// Create a custom Readable stream
513+
const myReadableStream = new Readable({
514+
objectMode: true,
515+
read(size) {
516+
// Push some data onto the stream
517+
this.push({ message: 'Hello, world!' });
518+
this.push(null); // Mark the end of the stream
519+
}
520+
});
521+
522+
// Consume the stream
523+
myReadableStream.on('data', (chunk) => {
524+
console.log(chunk);
525+
});
526+
527+
// Output:
528+
// { message: 'Hello, world!' }
529+
```
530+
In this example, we create a custom Readable stream that pushes a single object
531+
onto the stream using [`.push()`][]. The [`._read()`][] method is called when the stream is ready
532+
to consume data, and in this case, we immediately push some data onto the stream and
533+
mark the end of the stream by pushing null.
534+
535+
We then consume the stream by listening for the 'data' event and logging each chunk of
536+
data that is pushed onto the stream. In this case, we only push a single chunk of data
537+
onto the stream, so we only see one log message.
538+
507539
## Rules specific to Writable Streams
508540

509541
Recall that a [`.write()`][] may return true or false dependent on some

0 commit comments

Comments
 (0)