Node.js管道http请求&承诺

时间:2017-01-26 11:14:01

标签: node.js http stream es6-promise

我使用Node.js request模块发出http请求,并希望将响应传递给某些流。这是两个代码片段:

正常运作的示例。我只是管道来自response事件的回复。

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))

效果不正常。我在promise resolve回调中将响应传递给then回调一个promise和pipe。从第一种正常工作的方法来看,这种方法的文件大小更加平静。

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))

请告诉我为什么第二个例子也不能正常工作?

1 个答案:

答案 0 :(得分:0)

这很奇怪。我使用http模块而不是请求...

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));