Saturday, 22 April 2017

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?



via user3677331

No comments:

Post a Comment