Skip to content

Instantly share code, notes, and snippets.

@marcieltorres
Created August 25, 2018 02:07
Show Gist options
  • Save marcieltorres/3cdc1db585b842bb4da4df8083cffc89 to your computer and use it in GitHub Desktop.
Save marcieltorres/3cdc1db585b842bb4da4df8083cffc89 to your computer and use it in GitHub Desktop.
NodeJS: Getting the S3 object content with the AWS Lambda Function
var aws = require('aws-sdk');
var s3 = new aws.S3();
exports.handler = (event, context, callback) => {
//Verifica se o objeto existe (chamada através de evento no S3)
if ((event) && (event.Records) && (event.Records[0]) && (event.Records[0].s3) && (event.Records[0].s3.bucket) && (event.Records[0].s3.object)){
//Recupera informações de bucket e do objeto
var _bucket = event.Records[0].s3.bucket.name;
var _key = event.Records[0].s3.object.key;
if ((_bucket) && (_key)){
var _content = null;
getContentObject(_bucket, _key).then(function(v) { // `delay` returns a promise
_content = v;
//Verifica se tem conteúdo no arquivo
if(_content){
/*TODO */
}
else {
deleteObject(_bucket, _key);
}
}).catch(function(v) {
//Se ocorreu algum erro na leitura do arquivo, então remove o arquivo do bucket
deleteObject(_bucket, _key);
});
}
}
// TODO implement
callback(null, 'Hello from Lambda');
};
function getContentObject(bucket, key){
return new Promise(function(resolve, reject) {
// Only `delay` is able to resolve or reject the promise
s3.getObject({ Bucket: bucket, Key: key}, function(err, data) {
if (err){
console.log(err, err.stack);
resolve(null);
}
else {
resolve(data.Body.toString('utf-8'));
}
});
});
}
function deleteObject(bucket, key){
s3.deleteObject({ Bucket: bucket, Key: key}, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment