node.js异步:裁剪图像并上传到服务器

时间:2017-09-19 08:36:10

标签: javascript node.js express asynchronous gm

我想将图片裁剪成各种尺寸并将其上传到AWS S3。裁剪大小存储在数组中。

我正在使用async瀑布和series方法来实现这一目标。

async.each(crop_sizes,function (result,cb) {

            async.waterfall([
                /*
                 * Crop the images to specific size
                 */
                function (callback) {
                    gm(path)
                        .resize(result.width,result.height,'^')
                        .stream(function (err,buffer) {
                            console.log('cropped')
                            callback(null,{'buffer':buffer,'filename':filename,'s3':s3});
                        });
                },
                function (output,callback) {
                    var params ={
                        Bucket:'mybucket',
                        Key:'artwork-croppedimages/'+result.folder+output.filename,
                        Body:output.buffer
                    }

                    var options ={
                        partSize: 5242880, queueSize: 1
                    };

                    s3.upload(params,options,function(err, data) {
                        console.log("upload");

                        callback();
                    });
                }

            ],function (err,result) {
                console.log("one iteration completed");
                cb();
            });
        },function (err,result) {
            console.log("All upload complete");
        });

这是代码的执行方式:

重复async.each中的步骤1和2。

  1. 裁剪图像。

  2. 将裁剪后的图像上传到AWS S3。

  3. 但是在上传大尺寸图片时失败了。这是我得到的输出:

    cropped
    cropped
    cropped
    cropped
    cropped
    cropped
    cropped
    cropped
    cropped
    cropped
    cropped
    cropped
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    upload
    one iteration completed
    All upload complete
    

    预期产出:

     cropped
       upload
       one iteration completed
      cropped
       upload
       one iteration completed
       .....
      All upload complete
    

1 个答案:

答案 0 :(得分:0)

你可以尝试async.eachOfSeries功能吗?我怀疑async.each函数并行运行iteratee(如文档中所述),这必然导致问题。