如何在不写入磁盘的情况下直接将Express响应作为ExpressJS响应发送

时间:2015-09-17 14:25:27

标签: node.js http buffer

我正在尝试使用HTTP模块从URL请求图像,然后直接将响应的内容作为我的ExpressJS应用程序给出的响应发送(不首先将图像请求响应写入磁盘)。基本上,我想将文件从其外部URL下载到我的应用服务器的内存中,然后将其作为响应发送。

这是我到目前为止所拥有的:

 var http = require('http');
 var imageUrl = 'http://vignette3.wikia.nocookie.net/clubpenguinpookie/images/d/d0/Extremely-cute-kitten_large.jpg/revision/latest?cb=20140614000321';

 var req = http.request( imageUrl  , function(response) {

    var contents = [];
    var content_length = 0;

    response.setEncoding('binary');

    response.on('data', function (chunk) {
      contents.push( chunk );
      content_length += chunk.length;
    });

    response.on('end', function() {

      res.set('Content-Type', 'image/jpeg');
      res.set('Content-Length', content_length );

      contents.forEach(function(chunk){
        res.send( chunk );
      });

      res.end();
    })

});      

req.end();

从上面可以看出,我将请求响应存储为数组中的一系列块。然后我使用ExpressJS响应对象发送每个块。当我在浏览器中点击此端点时,我得到了正确的内容类型和长度标题,以及一些数据,但图片没有加载,Firefox告诉我它包含错误。

1 个答案:

答案 0 :(得分:1)

只需设置适当的标题并将流管道连接在一起。例如:

var http = require('http');
var imageUrl = 'http://vignette3.wikia.nocookie.net/clubpenguinpookie/images/d/d0/Extremely-cute-kitten_large.jpg/revision/latest?cb=20140614000321';

http.get(imageUrl, function(response) {
  if (response.statusCode !== 200) {
    res.statusCode = 500;
    return res.end();
  }

  res.set('Content-Type', 'image/jpeg');
  response.pipe(res);
});

管道更简单,确保没有二进制数据转换问题,并且它允许流背压做它的事情。

相关问题