Streaming payloads

Since the instance returned from http.request is a writable stream, we can take an input stream and pipe it to the POST request as data.

In this case, we want to notify the server that we'll be incrementally writing the request body to the server in chunks.

Let's copy the main recipe folder to a new folder, and call it streaming-payloads.

Now we'll tweak the index.js file slightly.

Let's make the top of the file look like so:

const http = require('http') 
const opts = {
method: 'POST',
hostname: 'reqres.in',
port: 80,
path: '/api/users',
headers: {
'Content-Type': 'application/json',
'Transfer-Encoding': 'chunked'
}
}

The payload assignment has been completely removed and we've replaced the Content-Length header with a Transfer-Encoding headed, set to chunked.

At the bottom of the file, we can replace the line req.end(payload) with:

http.get('http://reqres.in/api/users', (res) => { 
res.pipe(req)
})

We've initialized a stream of JSON from reqres.in (res) and piped it directly to request object (req).

When we run our script, we should see something like the following:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.225