奇怪的 node.js + http + gm + s3 行为

Strange node.js + http + gm + s3 behavior

此 node.js 代码块的目的是下载图像,调整大小,将调整后的图像上传到 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;
        }
    });                        
    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;
});

为什么第二个例子可以上传缩略图,第一个不能?

我想通了。

成功后http.get我使用下面的代码创建一个re-usable缓冲区。

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