2017-01-27 39 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 
});