Created
May 12, 2018 08:39
-
-
Save Troy-Yang/436a62fb14d9e07e1aa3534f1c351050 to your computer and use it in GitHub Desktop.
auto upload content to s3 bucket
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
{ | |
"accessKeyId": "xxxxx", | |
"secretAccessKey": "xxxxxxx", | |
"region": "ap-northeast-1" | |
} |
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
var path = require("path"); | |
var fs = require('fs'); | |
var mime = require('mime'); | |
var AWS = require('aws-sdk'); | |
AWS.config.loadFromPath('./s3-deploy/config.json'); | |
let s3 = new AWS.S3(); | |
const uploadDir = function (s3Path, bucketName) { | |
function walkSync(currentDirPath, callback) { | |
fs.readdirSync(currentDirPath).forEach(function (name) { | |
var filePath = path.join(currentDirPath, name); | |
var stat = fs.statSync(filePath); | |
if (stat.isFile()) { | |
callback(filePath, stat); | |
} else if (stat.isDirectory()) { | |
walkSync(filePath, callback); | |
} | |
}); | |
} | |
walkSync(s3Path, function (filePath, stat) { | |
let bucketPath = filePath.substring(s3Path.length + 1); | |
let mimeType = mime.getType(bucketPath); | |
let params = { | |
Bucket: bucketName, | |
Key: bucketPath.replace(/\\/g, '/'), | |
Body: fs.readFileSync(filePath), | |
ContentType: mimeType | |
}; | |
s3.putObject(params, function (err, data) { | |
if (err) { | |
console.log(err) | |
} else { | |
console.log('Successfully uploaded ' + bucketPath + ' to ' + bucketName); | |
} | |
}); | |
}); | |
}; | |
uploadDir("public", "images.troyyang.com"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment