m90
m90

Reputation: 11822

How can I re-use WriteStream's content in node.js

My app needs a ton of white placeholder PNG in different sizes that I cannot create manually.

Therefore I built me a service building these images on the fly using pngjs. This works fine. Now I was thinking caching the results on disk might be a good idea but I have no clue how to reuse the image content that I already piped into the server's response (as I am lacking a proper understanding of pipes probably).

My code looks like:

app.get('/placeholder/:width/:height', function(req, res){

  var fileLocation = __dirname + '/static/img/placeholder/' + req.params.width + 'x' + req.params.height + '.png';

  fs.readFile(fileLocation, function(err, file){

    if (file){

      res.sendfile(fileLocation);

    } else {

      var png = new PNG({
        width: parseInt(req.params.width, 10),
        height: parseInt(req.params.height, 10),
        filterType: -1
      });

      // image creation going on..

      //now all I get working is either doing:
      png.pack().pipe(res);
      //or
      png.pack().pipe(fs.createWriteStream(fileLocation));

    }

  });

});

But what I would like to do is use the png.pack()'s output to be sent as the req's response and written to disk simultaneously. I tried something along the lines of:

var output = png.pack();
output.pipe(fs.createWriteStream(fileLocation));

res.setHeader('Content-Type', 'image/png');
res.send(output, 'binary');

But it does not seem to work properly.

Upvotes: 0

Views: 283

Answers (1)

Jonathan Ong
Jonathan Ong

Reputation: 20325

you can pipe to multiple streams!

var output = png.pack()
output.pipe(fs.createWriteStream(fileLocation))
res.setHeader('Content-Type', 'image/png')
output.pipe(res)

Upvotes: 2

Related Questions