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:
parent
7c6031f4c1
commit
3898eff16c
21
README.md
21
README.md
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue