【问题标题】:Strange node.js + http + gm + s3 behavior奇怪的 node.js + http + gm + s3 行为
【发布时间】:2017-06-13 15:53:08
【问题描述】:

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

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

【问题讨论】:

标签: node.js gm aws-sdk-nodejs


【解决方案1】:

我想通了。

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

【讨论】:

    猜你喜欢
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多