Node.JS readStream在writeStream之前意外关闭

时间:2017-04-22 09:28:01

标签: javascript node.js

我正在尝试从远程服务器获取PDF文件,并将它们直接传回请求客户端,如下所示:

var writeStream = fs.createWriteStream(filename);
writeStream.on('close', function () {
    console.log("Closed write stream");
});
writeStream.on('open', function () {
    console.log('Open event for writestream');
});
writeStream.on('pipe', function () {
    console.log('pipe event for writestream');
    var rd = fs.createReadStream(filename);
    rd.on('open', function () {
        console.log('Open event for readstream');
    });
    rd.on('close', function () {
        console.log("Closed read stream");
    }).pipe(res);
});
request(pQuestURL)
    .on('error', function (err) {
        console.log(err);
        res.json({ status: -1, message: 'Maps error, check your parameters' });
    })
    .pipe(writeStream);

但它给我的输出如下:

pipe event for writestream
Open event for writestream
Open event for readstream
Closed read stream
Closed write stream

我期待readstream仅在writestream完成后完成。 readstream似乎立即关闭,因此我的客户端收到空响应,而写入流仅在下载整个pdf后完成。我的理解中有漏洞吗?如何在不等待finish的{​​{1}}事件的情况下向后管道?

修改

实际上我可以将可读流保存在变量中并将其传输到我想要的尽可能多的可写流。我通过简化as:

完成了我的目标
writestream

1 个答案:

答案 0 :(得分:2)

主要问题是readStream更快,因为writeStream取决于下载速度。因此,您可以直接向用户流式传输:

 request(pQuestURL).pipe(res);

或者,您可以等待writeStreams数据事件,并检索writeStream的一大块。然而,在我看来这是不必要的......