Skip to content

Commit

Permalink
doc: added example for Readable stream back-pressure (#5066)Co-author…
Browse files Browse the repository at this point in the history
…ed-by: Claudio Wunder <cwunder@gnome.org>

* added example for back-pressure

Signed-off-by: Rishabh Bhandari <rishabhbhandari6@gmail.com>

* linting fixes

Signed-off-by: Rishabh Bhandari <rishabhbhandari6@gmail.com>

---------

Signed-off-by: Rishabh Bhandari <rishabhbhandari6@gmail.com>
Co-authored-by: Claudio Wunder <cwunder@gnome.org>
  • Loading branch information
RishabhKodes and ovflowd authored Feb 27, 2023
1 parent 903c1c6 commit 78c1867
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions locale/en/docs/guides/backpressuring-in-streams.md
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,38 @@ readable.on('data', (data) =>
);
```

Here's an example of using [`.push()`][] with a Readable stream.

```javascript
const { Readable } = require('stream');

// Create a custom Readable stream
const myReadableStream = new Readable({
objectMode: true,
read(size) {
// Push some data onto the stream
this.push({ message: 'Hello, world!' });
this.push(null); // Mark the end of the stream
}
});

// Consume the stream
myReadableStream.on('data', (chunk) => {
console.log(chunk);
});

// Output:
// { message: 'Hello, world!' }
```
In this example, we create a custom Readable stream that pushes a single object
onto the stream using [`.push()`][]. The [`._read()`][] method is called when the stream is ready
to consume data, and in this case, we immediately push some data onto the stream and
mark the end of the stream by pushing null.

We then consume the stream by listening for the 'data' event and logging each chunk of
data that is pushed onto the stream. In this case, we only push a single chunk of data
onto the stream, so we only see one log message.

## Rules specific to Writable Streams

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

0 comments on commit 78c1867

Please sign in to comment.