Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Created May 20, 2014 21:51
Show Gist options
  • Save bouzuya/7f757c923538b9f24db2 to your computer and use it in GitHub Desktop.
Save bouzuya/7f757c923538b9f24db2 to your computer and use it in GitHub Desktop.
Amazon S3 upload
var Promise = require('q').Promise;
var fs = require('fs');
var path = require('path');
var S3 = require('aws-sdk').S3;
var readFile = function(file, options) {
var opts = (options || {}).text ? { encoding: 'utf-8' } : {};
return fs.readFileSync(file, opts);
};
var CONTENT_TYPES = [
{ extName: '.html', value: 'text/html' },
{ extName: '.css', value: 'text/css' },
];
var getContentType = function(file) {
var extName = path.extname(file);
var contentTypes = CONTENT_TYPES.filter(function(contentType) {
return contentType.extName === extName;
});
if (contentTypes.length <= 0) {
throw new Error('unknown extname: ' + extName);
}
var contentType = contentTypes[0]
return contentType.value;
};
var getFiles = function(dir) {
var filePaths = getFilePaths(publicDir);
return filePaths.map(function(filePath) {
return {
// /path/to/entry/public
root: dir,
// /path/to/entry/public/yyyy/mm/dd/index.html
absolutePath: filePath,
// yyyy/mm/dd/index.html
relativePath: path.relative(publicDir, filePath),
// index.html
fileName: path.basename(filePath),
// index
baseName: path.basename(filePath, path.extname(filePath)),
// .html
extName: path.extname(filePath),
};
});
};
var getFilePaths = function(dir) {
return fs.readdirSync(dir).reduce(function(files, file) {
var filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
return files.concat(getFilePaths(filePath));
} else {
files.push(filePath);
return files;
}
}, []);
};
var eachSeries = function(arr, f) {
return arr.reduce(function(promise, item) {
return promise.then(function() { return f(item); });
}, new Promise(function(resolve) { resolve(); }));
};
var getDirName = function() {
var publicDir = './public';
return publicDir;
};
var getBucketName = function() {
var bucketName = process.env.BUCKET_NAME;
return bucketName;
};
var toParams = function(files) {
return files.map(function(file) {
return {
Bucket: bucketName,
Key: file.relativePath,
ACL: 'public-read',
Body: readFile(file, { text: false }),
ContentType: getContentType(file),
};
});
};
var upload = function() {
var from = getDirName();
var to = getBucketName();
var files = getFiles(from);
var paramsArray = toParams(files);
var s3 = new S3({ apiVersion: '2006-03-01' });
eachSeries(paramsArray, function(params) {
return new Promise(function(resolve, reject) {
s3.putObject(params, function(err, data) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
};
module.exports = upload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment