Infra/AWS

How to upload file to s3 bucket using aws-sdk on node.js

하우아유두잉 2019. 12. 23. 18:11

 

버킷 생성

 

 

 

 


IAM 생성

 

소스코드

// example.js
const fs = require("fs");
const AWS = require("aws-sdk");
const s3  = new AWS.S3({
  accessKeyId: process.env.ACCESS_KEY_ID,
  secretAccessKey: process.env.SECRET_ACCESS_KEY
});

export const uploadLogFiles = () => {
    return new Promise((resolve: any, reject: any) => {
        fs.readdir("./log", function (err: any, filenames: any) {
            if (err) {
                console.log("ERROR IN READING LOG FILES FROM /log FOLDER");
                console.log(err);
                return;
            }
            console.log(filenames);
            filenames.forEach(function (filename: string) {
                fs.readFile("./log/" + filename, `utf-8`, function (err: any, content: any) {
                    if (err) {
                        console.log("ERROR IN LOOPING INDIVIDUAL FILES");
                        console.log(err);
                        reject(err);
                    }
                    const params = {
                        Bucket: "[BUCKET_NAME]",
                        Key: "log/" + filename,
                        Body: content
                    };
                    s3.upload(params, function (s3Err: any, data: any) {
                        if (s3Err) {
                            console.log("ERROR IN UPLOADING LOGS TO S3");
                            console.log(s3Err);
                            reject(s3Err);
                        }
                        console.log(`File uploaded successfully at ${data.Location}`);
                        resolve("LOGS UPLOADED SUCCESSFULLY");
                    });
                });
            });
        });
    });
};

 

 

실행

$ node example.js

 

 

확인

aws s3