aws nodejs upload file to s3 code example

Example 1: how to upload file to s3 nodejs

const fs = require('fs');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
    accessKeyId: process.env.AWS_ACCESS_KEY,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});

const fileName = 'contacts.csv';

const uploadFile = () => {
  fs.readFile(fileName, (err, data) => {
     if (err) throw err;
     const params = {
         Bucket: 'testBucket', // pass your bucket name
         Key: 'contacts.csv', // file will be saved as testBucket/contacts.csv
         Body: JSON.stringify(data, null, 2)
     };
     s3.upload(params, function(s3Err, data) {
         if (s3Err) throw s3Err
         console.log(`File uploaded successfully at ${data.Location}`)
     });
  });
};

uploadFile();

Example 2: how to download array of files from aws s3 using aws sdk in nodejs

const exec = require('child_process').exec;
exec('aws s3 sync s3://yourbucket .', (err, stdout, stderr) => {});

Example 3: how to download array of files from aws s3 using aws sdk in nodejs

function listFiles(cb) {
    s3.stuff(params, cb);
}
function downlaodFile(key, cb) {
    s3.stuff(key, cb);
}
listFiles(function (err, fileKeys) {
    if (err) {
        throw err;//don't really but this is just an example
    }
    async.each(fileKeys, downloadFile, function done(err) {
        if (err) {
            throw err;
        }
    });
});