Skip to content

Commit 2e79b62

Browse files
authored
chore(docs): add request() example for conditionally reading the body (#3743)
1 parent eac8ed4 commit 2e79b62

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

docs/docs/api/Dispatcher.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@ try {
527527
console.log('headers', headers)
528528
body.setEncoding('utf8')
529529
body.on('data', console.log)
530+
body.on('error', console.error)
530531
body.on('end', () => {
531532
console.log('trailers', trailers)
532533
})
@@ -630,6 +631,25 @@ try {
630631
}
631632
```
632633

634+
#### Example 3 - Conditionally reading the body
635+
636+
Remember to fully consume the body even in the case when it is not read.
637+
638+
```js
639+
const { body, statusCode } = await client.request({
640+
path: '/',
641+
method: 'GET'
642+
})
643+
644+
if (statusCode === 200) {
645+
return await body.arrayBuffer()
646+
}
647+
648+
await body.dump()
649+
650+
return null
651+
```
652+
633653
### `Dispatcher.stream(options, factory[, callback])`
634654

635655
A faster version of `Dispatcher.request`. This method expects the second argument `factory` to return a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream which the response will be written to. This improves performance by avoiding creating an intermediate [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) stream when the user expects to directly pipe the response body to a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream.

0 commit comments

Comments
 (0)