From 06afb272bc1ddba89b827cfcea17f82d40784c27 Mon Sep 17 00:00:00 2001 From: Szymon Marczak <36894700+szmarczak@users.noreply.github.com> Date: Fri, 12 Jul 2019 11:54:12 +0200 Subject: [PATCH] Encourage using `Stream.pipeline()` --- migration-guides.md | 13 +++++++++++-- readme.md | 20 ++++++++++++++++---- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/migration-guides.md b/migration-guides.md index 50263912c..99fed8ee3 100644 --- a/migration-guides.md +++ b/migration-guides.md @@ -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 + ); } }); ``` diff --git a/readme.md b/readme.md index 02d9758c8..5eb3e674f 100644 --- a/readme.md +++ b/readme.md @@ -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