Dmitriy
Dmitriy

Reputation: 703

Node.js pipe http request & Promises

I use a Node.js request module to make a http request and want to pipe the response to some stream. Here are two code fragments:

A properly working example. I just pipe a response from response event.

const fs = require('fs')
const path = require('path')
const request = require('request')

const filepath = path.resolve('./tmp.zip')
const ws = fs.createWriteStream(filepath)

function get() {
    return new Promise((resolve, reject) => {
        request.get(uri, options)
            .on('response', (res) => {
                ws.on('finish', () => console.log('finish'))
                res.pipe(ws)
                resolve()
            })
            .on('error', (err) =>  {
                reject(err)
            })
    })
}

get().then(() => {
    console.log('done')
}).catch((err) => console.log(err))

Not properly working example. I pass the response into resolve callback of a promise and pipe from them on promise then callback. The file size of this approach is smoller then from the first properly working approach.

const fs = require('fs')
const path = require('path')
const request = require('request')

const filepath = path.resolve('./tmp.zip')
const ws = fs.createWriteStream(filepath)

function get() {
    return new Promise((resolve, reject) => {
        request.get(uri, options)
            .on('response', (res) => {
                resolve(res)
            })
            .on('error', (err) =>  {
                reject(err)
            })
    })
}

get().then((res) => {
    ws.on('finish', () => console.log('finish'))
    res.pipe(ws)
}).catch((err) => console.log(err))

Please, tell why the second example doesn't working properly as well?

Upvotes: 2

Views: 4756

Answers (1)

That's strange. I made it work with http module not with request...

const fs = require('fs');
const path = require('path');
const http = require('http');

const filepath = path.resolve('./index.html');
const ws = fs.createWriteStream(filepath);
const options = {
    hostname: "your_url",
    port: "80", 
    path: "/index.html"
};

function get() {
    return new Promise((resolve, reject) => {
        http.get(uri, function(res) {
            resolve(res);
        });
    });
}

get().then(function(res) {
    console.log('then');
    ws.on('finish', () => {
        console.log('finish');
    })
    res.pipe(ws);
}).catch((err) => console.log(err));

Upvotes: 1

Related Questions