Last active
August 21, 2019 02:57
-
-
Save jnayak1/3ac62fce05485e62ad379892a21a80ae to your computer and use it in GitHub Desktop.
Node.js AWS Lambda function for creating thumbnails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require('aws-sdk'); | |
const sharp = require('sharp'); | |
const stream = require('stream'); | |
const WIDTH = 200; | |
const S3 = new AWS.S3(); | |
exports.handler = (event, context) => { | |
event.Records.forEach((record, index, array) => { | |
var bucket = record.s3.bucket.name; | |
var key = record.s3.object.key; | |
if(key.includes("thumbnail-")) return; | |
var fileName = key.substr(key.lastIndexOf('/') + 1); | |
var prefix = key.substring(0, key.lastIndexOf('/') + 1); | |
var newKey = prefix + "thumbnail-" + fileName; | |
console.log("bucket:", bucket, "key:", key, "fileName:", fileName, "newKey:", newKey); | |
var resizeTransform = sharp().resize(WIDTH, undefined); | |
S3.upload({ | |
Bucket: bucket, | |
Key: newKey, | |
Body: | |
S3.getObject({ | |
Bucket: bucket, Key: key | |
}).createReadStream().pipe(resizeTransform) | |
}, function(err,data){ | |
if (err) | |
context.fail(err) | |
else | |
context.succeed(); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment