chore(docs): add request() example for conditionally reading the body#3743
chore(docs): add request() example for conditionally reading the body#3743mcollina merged 3 commits intonodejs:mainfrom
Conversation
| ```js | ||
| const { body, statusCode } = await client.request({ | ||
| path: '/', | ||
| method: 'GET' | ||
| }) | ||
| | ||
| body.on('error', console.error) // prevent process from crashing on error | ||
| | ||
| if (statusCode === 200) { | ||
| const buffer = await body.arrayBuffer() | ||
| return buffer | ||
| } | ||
| | ||
| for await (const _chunk of body) { | ||
| // force consumption of body to avoid memory leak | ||
| } | ||
| return null | ||
| ``` |
There was a problem hiding this comment.
| ```js | |
| const { body, statusCode } = await client.request({ | |
| path: '/', | |
| method: 'GET' | |
| }) | |
| body.on('error', console.error) // prevent process from crashing on error | |
| if (statusCode === 200) { | |
| const buffer = await body.arrayBuffer() | |
| return buffer | |
| } | |
| for await (const _chunk of body) { | |
| // force consumption of body to avoid memory leak | |
| } | |
| return null | |
| ``` | |
| ```js | |
| const { body, statusCode } = await client.request({ | |
| path: '/', | |
| method: 'GET' | |
| }) | |
| if (statusCode === 200) { | |
| return await body.arrayBuffer() | |
| } | |
| await body.dump() | |
| return null |
There was a problem hiding this comment.
@ronag @mcollina I think its important to keep the body.on('error', console.error) handler because any code added between the client.request() and the await body calls could throw and then it would be uncatchable.
Since this example is about conditional code, I think its best practice to keep it in there to avoid this footgun.
There was a problem hiding this comment.
Furthermore, I don't think await body.dump() is sufficient.
It says it defaults to 131072 but what if the body is larger than that?
Line 254 in 8e025d1
There was a problem hiding this comment.
handler because any code added between the client.request() and the await body calls could throw and then it would be uncatchable.
That would be incorrect code anyway...
It says it defaults to 131072 but what if the body is larger than that?
It will close the connection if the body is larger.
Co-authored-by: Robert Nagy <ronagy@icloud.com>
Co-authored-by: Ethan Arrowood <ethan@arrowood.dev>
| @Ethan-Arrowood PTAL |
| What about @styfle 's comment / question here: #3743 (comment) Is dump sufficient if the body is larger than its limit? |
Ethan-Arrowood left a comment
There was a problem hiding this comment.
lgtm - but there is still the outstanding question about .dump() limits
This relates to...
Documentation for dispatcher.request()
Rationale
It is very easy to cause a memory leak or even crash the process if you forget to handle the response body.
Changes
A new example showing how to conditionally reading the body
Features
N/A
Bug Fixes
N/A
Breaking Changes and Deprecations
N/A
Status