docs: Add more complete stream download example (#645)

* Add more complete stream download example

* Change header size

Co-authored-by: Antoni Kepinski <xxczaki@pm.me>
This commit is contained in:
John Lees-Miller 2020-04-15 10:00:15 +01:00 committed by GitHub
parent 7c6031f4c1
commit 3898eff16c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 9 deletions

View File

@ -267,18 +267,21 @@ Cookies are not stored by default. However, cookies can be extracted and passed
### Streams
The "Node.js way" is to use streams when possible:
The "Node.js way" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.
```js
const {createWriteStream} = require('fs');
const fetch = require('node-fetch');
const util = require('util');
const fs = require('fs');
const streamPipeline = util.promisify(require('stream').pipeline);
fetch(
'https://octodex.github.com/images/Fintechtocat.png'
).then(res => {
const dest = fs.createWriteStream('./octocat.png');
res.body.pipe(dest);
});
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => {
if (!res.ok) {
throw new Error(`unexpected response ${res.statusText}`);
}
return streamPipeline(res.body, fs.createWriteStream('./octocat.png'));
});
```
### Buffer