简体   繁体   中英

Node.JS readStream unexpectedly closes before writeStream

I'm trying to fetch PDF files from remote servers and pipe them right back to the requesting clients like below:

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

But it gives me output like below:

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

I was expecting the readstream to only finish after the writestream has finished. The readstream appears to close instantly and therefore my client receives an empty response while the writestream finishes only after downloading the whole pdf. Is there a hole in my understanding? How can I pipe right back without waiting for the finish event of the writestream ?

Edit:

Actually I can save the readable stream in a variable and pipe it to as many writable streams as I want. I accomplished my goal by simplifying the as:

var mapRequest = request(pQuestURL);
mapRequest.on('error', function (err) {
    console.log(err);
    res.json({ status: -1, message: 'Maps error, check your parameters' });
});
mapRequest.pipe(writeStream);
mapRequest.pipe(res);

The main problem is that the readStream is faster as the writeStream is dependend on the download speed. So you either stream to the user directly:

 request(pQuestURL).pipe(res);

Alternatively you could wait for the writeStreams data event, and retrieve a chunk of the writeStream. However this is unneccessary in my opinion...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM