Skip to content

Instantly share code, notes, and snippets.

@wytanj
Forked from jlouros/aws.upload-folder-to-s3.js
Created October 21, 2019 06:40
Show Gist options
  • Select an option

  • Save wytanj/e3b37f85adb3a72a3874ed5a74a05992 to your computer and use it in GitHub Desktop.

Select an option

Save wytanj/e3b37f85adb3a72a3874ed5a74a05992 to your computer and use it in GitHub Desktop.

Revisions

  1. @jlouros jlouros revised this gist May 10, 2017. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions aws.upload-folder-to-s3.js
    Original file line number Diff line number Diff line change
    @@ -28,6 +28,11 @@ fs.readdir(distFolderPath, (err, files) => {

    // get the full path of the file
    const filePath = path.join(distFolderPath, fileName);

    // ignore if directory
    if (fs.lstatSync(filePath).isDirectory()) {
    continue;
    }

    // read file contents
    fs.readFile(filePath, (error, fileContent) => {
  2. @jlouros jlouros created this gist May 3, 2017.
    48 changes: 48 additions & 0 deletions aws.upload-folder-to-s3.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    const AWS = require("aws-sdk"); // from AWS SDK
    const fs = require("fs"); // from node.js
    const path = require("path"); // from node.js

    // configuration
    const config = {
    s3BucketName: 'your.s3.bucket.name',
    folderPath: '../dist' // path relative script's location
    };

    // initialize S3 client
    const s3 = new AWS.S3({ signatureVersion: 'v4' });

    // resolve full folder path
    const distFolderPath = path.join(__dirname, config.folderPath);

    // get of list of files from 'dist' directory
    fs.readdir(distFolderPath, (err, files) => {

    if(!files || files.length === 0) {
    console.log(`provided folder '${distFolderPath}' is empty or does not exist.`);
    console.log('Make sure your project was compiled!');
    return;
    }

    // for each file in the directory
    for (const fileName of files) {

    // get the full path of the file
    const filePath = path.join(distFolderPath, fileName);

    // read file contents
    fs.readFile(filePath, (error, fileContent) => {
    // if unable to read file contents, throw exception
    if (error) { throw error; }

    // upload file to S3
    s3.putObject({
    Bucket: config.s3BucketName,
    Key: fileName,
    Body: fileContent
    }, (res) => {
    console.log(`Successfully uploaded '${fileName}'!`);
    });

    });
    }
    });