Skip to content

Instantly share code, notes, and snippets.

@Troy-Yang
Created May 12, 2018 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Troy-Yang/436a62fb14d9e07e1aa3534f1c351050 to your computer and use it in GitHub Desktop.
Save Troy-Yang/436a62fb14d9e07e1aa3534f1c351050 to your computer and use it in GitHub Desktop.
auto upload content to s3 bucket
{
"accessKeyId": "xxxxx",
"secretAccessKey": "xxxxxxx",
"region": "ap-northeast-1"
}
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