Skip to content

Commit

Permalink
Encourage using Stream.pipeline()
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak committed Jul 12, 2019
1 parent 3ba7d4a commit 06afb27
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
13 changes: 11 additions & 2 deletions migration-guides.md
Expand Up @@ -144,13 +144,22 @@ http.createServer((request, response) => {
The cool feature here is that Request can proxy headers with the stream, but Got can do that too:

```js
http.createServer((request, response) => {
const stream = require('stream');
const {promisify} = require('util');
const got = require('got');

const pipeline = promisify(stream.pipeline);

http.createServer(async (request, response) => {
if (request.url === '/doodle.png') {
// When someone makes a request to our server, we receive a body and some headers.
// These are passed to Got. Got proxies received data to our server response,
// so you don't have to do `response.writeHead(statusCode, headers)` and `response.end(body)`.
// It's done automatically.
request.pipe(got.stream('https://example.com/doodle.png')).pipe(response);
await pipeline(
got.stream('https://example.com/doodle.png'),
response
);
}
});
```
Expand Down
20 changes: 16 additions & 4 deletions readme.md
Expand Up @@ -78,16 +78,28 @@ const got = require('got');
###### Streams

```js
const stream = require('stream');
const {promisify} = require('util');
const fs = require('fs');
const got = require('got');

got.stream('https://sindresorhus.com').pipe(fs.createWriteStream('index.html'));
const pipeline = promisify(stream.pipeline);

// For POST, PUT, and PATCH methods `got.stream` returns a `stream.Writable`
fs.createReadStream('index.html').pipe(got.stream.post('https://sindresorhus.com'));
(async () => {
await pipeline(
got.stream('https://sindresorhus.com'),
fs.createWriteStream('index.html')
);

// For POST, PUT, and PATCH methods `got.stream` returns a `stream.Writable`
await pipeline(
fs.createReadStream('index.html'),
got.stream.post('https://sindresorhus.com')
);
})();
```

**Note:** `from.pipe(to)` doesn't forward errors. Instead you can use [`Stream.pipeline(from, to, callback)`](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) which catches them.
**Tip:** Using `from.pipe(to)` doesn't forward errors. If you use it, switch to [`Stream.pipeline(from, ..., to, callback)`](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) instead (available from Node v10).

### API

Expand Down

0 comments on commit 06afb27

Please sign in to comment.