如何在node.js中重用WriteStream的内容

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

本文关键字:WriteStream node js      更新时间:2023-09-26

我的应用程序需要大量不同大小的白色占位符 PNG,我无法手动创建。

因此,我

为我构建了一个服务,使用 pngjs 即时构建这些图像。这工作正常。现在我认为在磁盘上缓存结果可能是一个好主意,但我不知道如何重用我已经通过管道传输到服务器响应中的图像内容(因为我缺乏对管道的正确理解可能)。

我的代码如下所示:

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

但是我想做的是使用png.pack()的输出作为req的响应发送并同时写入磁盘。我尝试了类似以下内容:

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

但它似乎不能正常工作。

你可以通过管道连接到多个流!

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