Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
const AWS = require('aws-sdk');
const fs = require('fs');
const mime = require('mime-types')
const path = require("path");
// Base AWS config.
// AWS Reference: Make sure the profile exists in ~/.aws/credentials
// See managing access keys:
const config = {
s3_bucket_name: 'whatever-bucket-name',
build_path: './build', // local build path
aws_profile: 'your-aws-profile',
target_path:"subfolder-in-bucket" //this will put files in a subfolder
//Load profile ID and key secret
const credentials = new AWS.SharedIniFileCredentials({
profile: config.aws_profile
//Update AWS config
AWS.config.credentials = credentials;
//Create a new S3 object
const s3 = new AWS.S3();
const build_folder_path = path.join(__dirname, config.build_path.replace(/^\/+/g, ''));
// removes the root path: ie /user/dave/projects/project/build from /user/dave/projects/project/build/index.html
// so you get /index.html - then it removes the leading slash to give you index.html
// then it adds the target_path ie: folder/index.html
// it uses this as the file key name for the AWS s3
const normalize_base_path = (file_path) =>{
return path.join(config.target_path,file_path.replace(build_folder_path,"").replace(/^\/+/g, ''))
const upload_file = (file_path) => {
fs.readFile(file_path, (error, file_buffer) => {
// if unable to read file contents, throw exception
if (error) {
throw error;
//we only want the path from the build folder
const rel_path = normalize_base_path(file_path)
//get the mime type of the file for the AWS Content Type
const mimetype = mime.lookup(file_path)
console.log(`'${file_path}:'Mime type not found. Skipping file!`)
//upload file to S3
Bucket: config.s3_bucket_name,
Key: rel_path,
Body: file_buffer
}, (res) => {
console.log(`Wrote: '${rel_path}'`);
const upload_folder = (folder_path) => {
fs.readdir(folder_path, (err, files) => {
if (!files || files.length === 0) {
console.log(`provided folder '${build_folder_path}' is empty or does not exist.`);
console.log('Make sure your project was compiled!');
for (const f_name of files) {
// get the full path of the file
const f_path = path.join(folder_path, f_name);
//hit a directory, do recursion
if (fs.lstatSync(f_path).isDirectory()) {
}else {
//otherwise upload file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.