Skip to content

Instantly share code, notes, and snippets.

@riazXrazor
Created August 10, 2021 10:47
Show Gist options
  • Save riazXrazor/857f4a385762bd30d3ca0cf0b8ca95cc to your computer and use it in GitHub Desktop.
Save riazXrazor/857f4a385762bd30d3ca0cf0b8ca95cc to your computer and use it in GitHub Desktop.
Nodejs Script to Upload Files to AWS S3
const fs = require('fs');
const path = require('path');
const AWS = require('aws-sdk');
// to be filled by user
const env = {
MY_ACCESS_ID : '',
MY_ACCESS_SECRET_KEY: '',
MY_ACCESS_REGION: "ap-south-1",
MY_BUCKET_NAME: ''
}
AWS.config.update({
accessKeyId: env.MY_ACCESS_ID,
secretAccessKey: env.MY_ACCESS_SECRET_KEY,
region: "ap-south-1"
});
/**
*
* @param {string} file_path file path to be uploaded to S3
* @param {string} folder folder name that will be created in S3
* @param {function} callback after each file processed this callback function will be called
*/
const sendToS3 = function(file_path,folder,callback) {
console.log(`File: ${file_path} uploading... `);
fs.readFile(file_path, function (err, data) {
if (err) { throw err; }
const base64data = Buffer.from(data, 'binary');
const s3 = new AWS.S3();
s3.upload({
Bucket: env.MY_BUCKET_NAME,
Key: `${folder}/${path.basename(file_path)}`,
Body: base64data,
ACL: 'public-read'
},function (err,data) {
if (err){
console.log(`File: ${file_path} not uploaded`);
console.log(err, err.stack);
} else {
console.log(`File: ${file_path} uploaded `);
}
if(callback)
callback(err);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment