'use strict'; var s3 = new (require('aws-sdk')).S3(); var gm = require('gm').subClass({ imageMagick: true }); var async = require('async'); var imageTypeRegExp = /(?:(jpg)e?|(png))$/; var sizesConfigs = [ { width: 800, destinationPath: 'large' }, { width: 500, destinationPath: 'medium' }, { width: 200, destinationPath: 'small' }, { width: 45, destinationPath: 'thumbnail'} ]; exports.AwsHandler = function (event, context) { var s3Bucket = event.Records[0].s3.bucket.name; var s3Key = event.Records[0].s3.object.key; // Check if file has a supported image extension var imgExt = imageTypeRegExp.exec(s3Key); if (imgExt === null) { console.error('unable to infer the image type for key %s', s3Key); context.done(new Error('unable to infer the image type for key %s' + s3Key)); return; } var imageType = imgExt[1] || imgExt[2]; async.waterfall([ function download(next) { s3.getObject({ Bucket: s3Bucket, Key: s3Key }, next); }, function transform(response, next) { async.map(sizesConfigs, function (sizeConfig, mapNext) { gm(response.Body, s3Key) .resize(sizeConfig.width) .toBuffer(imageType, function (err, buffer) { if (err) { mapNext(err); return; } s3.putObject({ Bucket: s3Bucket, Key: 'dst/' + sizeConfig.destinationPath + '/' + s3Key, Body: buffer, ContentType: 'image/' + imageType }, mapNext) }); }, next); } ], function (err) { if (err) { console.error('Error processing image, details %s', err.message); context.done(err); } else { context.done(null, 'Successfully resized images bucket: ' + s3Bucket + ' / key: ' + s3Key); } }); };