Created
July 31, 2016 23:01
-
-
Save goosys/5472fec24eb824e4925230697bc6c048 to your computer and use it in GitHub Desktop.
unzip_hook_from_s3
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
'use strict'; | |
const aws = require('aws-sdk'); | |
const s3 = new aws.S3({apiVersion: '2006-03-01'}); | |
const node_zip = require('node-zip'); | |
const mime = require('mime-types'); | |
function lookup_mime( name ){ | |
console.log(name); | |
const mimetype = mime.lookup(name) || 'application/octet-stream'; | |
console.log(mimetype); | |
return mimetype; | |
} | |
exports.handler = function(event, context) { | |
const bucket = event.Records[0].s3.bucket.name; | |
const key = event.Records[0].s3.object.key; | |
Promise.resolve() | |
.then(function(){ | |
return new Promise(function(resolve, reject){ | |
s3.getObject( | |
{ Bucket: bucket, Key:key }, | |
function(error, data) { | |
if (error) { reject(error); } | |
else { resolve(data); } | |
} | |
); | |
}); | |
}) | |
.then(function(data){ | |
const zip = new node_zip(data.Body, {base64: false, checkCRC32: true}); | |
const dir = key.replace(/\.zip/,'/'); | |
return Promise.all(Object.keys(zip.files).map(function(i) { | |
return new Promise(function(resolve, reject){ | |
const f = zip.files[i]; | |
s3.putObject( | |
{ | |
Bucket: bucket, | |
Key : dir + f.name, | |
Body : new Buffer(f.asBinary(), 'binary'), | |
ContentType: lookup_mime( f.name ), | |
ACL : 'public-read' | |
}, | |
function (err) { | |
if (err) { reject(err); } | |
else{ resolve(); } | |
}); | |
}); | |
})); | |
}) | |
.then(function(){ | |
context.succeed(); | |
}) | |
.catch(function(mes){ | |
context.fail(mes); | |
}) | |
}; |
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
{ | |
"name": "unzip_hook_from_s3", | |
"version": "1.0.0", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "MIT", | |
"description": "", | |
"dependencies": { | |
"mime-types": "^2.1.11", | |
"node-zip": "^1.1.1", | |
"zip": "^1.2.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment