Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

doc: added example for Readable stream back-pressure (#5066)Co-authored-by: Claudio Wunder <cwunder@gnome.org> #5066

Merged
merged 3 commits into from
Feb 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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