2017-01-27 46 views
0

这个node.js代码块的目的是下载一个图片,调整它的大小,将调整大小的图片上传到s3,然后将原始图片上传到s3。奇怪的node.js + http + gm + s3行为

非工作代码:

http.get(url, function onResponse(res) { 
    gm(res) 
    .resize(250,250) 
    .stream(function(err, stdout, stderr){ 
     if(debug)console.log("Resized "+key+" and created "+key+"_thumb.jpg"); 
     if(err){ 
       console.log("Error resizing image. Message:",err); 
     } 
     else{ 
      var data = { 
       Bucket: 'bucket-name', 
       Key: key+"_thumb.jpg", 
       Body: stdout, 
       ACL: "public-read", 
       ContentType:"image/jpeg" 
      }; 
      s3 = new aws.S3() 
      s3.upload(data, function(err, resp) { 
       if(debug)console.log(resp); 
      }); 
      s3=null; 
      stdout=null; 
      data=null; 
     } 
    });       
    s3 = new aws.S3() 
    s3.upload({Bucket:"bucket-name", Key: key+".jpg", ACL:"public-read", ContentType:"image/jpeg" ,Body: res}, function(err,data){ 
     if(debug)console.log(data); 
     data=null; 
    }); 
    s3=null; 
    res=null; 
}); 

的问题是,由于预期该代码块不会运行。在上面的代码中,s3上传的缩略图总是一个空文件。

但是,如果我删除第二个s3上传请求,缩略图会奇迹般地开始正确上传。

工作代码:

http.get(url, function onResponse(res) { 
    gm(res) 
    .resize(250,250) 
    .stream(function(err, stdout, stderr){ 
     if(debug)console.log("Resized "+key+" and created "+key+"_thumb.jpg"); 
     if(err){ 
       console.log("Error resizing image. Message:",err); 
     } 
     else{ 
      var data = { 
       Bucket: 'bucket-name', 
       Key: key+"_thumb.jpg", 
       Body: stdout, 
       ACL: "public-read", 
       ContentType:"image/jpeg" 
      }; 
      s3 = new aws.S3() 
      s3.upload(data, function(err, resp) { 
       if(debug)console.log(resp); 
      }); 
      s3=null; 
      stdout=null; 
      data=null; 
     } 
    });       
    res=null; 
}); 

为什么我可以上传在第二个例子中的缩略图,但不是第一?

+0

好了,我认为解决的办法可能与此问题:http://stackoverflow.com/questions/19553837/node-js-piping-the-same-readable-stream-into-multiple-可写的目标 – Jack

回答

0

我想通了。

成功的http.get后,我使用下面的代码来创建一个可重用的缓冲区。

res.on('data', function(chunk) { 
    data.push(chunk); 
}).on('end', function() { 
    var imgbuffer = Buffer.concat(data); 
    //create thumbnail 
    //s3.upload thumbnail 
    //s3.upload original 
});