AWS - S3 (Nodejs)

Singsoong·2022년 7월 28일
0

AWS

목록 보기
2/14

📌개요

  • S3 : Simple Storage Service, 어떠한 정보를 저장하는 서비스, 파일을 저장하는 서비스
  • 보관은 해야하지만 접근할 필요가 없는 파일들 다른 타입으로 지정해 저렴하게 저장할 수 있다.
  • 컴퓨터의 하드디스크와 같은 저장장치를 말함 (네이버 myBox와 같은 클라우드라고 생각하면 될듯?)
  • 객체 : 버킷에 저장된 파일 하나하나를 객체라고 함
  • 버킷 : 객체가 파일이면, 버킷은 객체를 담는 최상위 디렉토리라고 생각하면 됨

📌버킷 생성(Nodejs)

  • IAM 사용자 생성 후 액세스 키 발급 받기
  • 액세스 키 ID: @@
  • 비밀 액세스 키 : @@
  • 버킷 이름은 모든 유저로 부터 고유해야 한다.
  • $ npm install aws-sdk —save
  • createBucket.js
const AWS = require("aws-sdk");
const ID = "@@";
const SECRET = "@@";
const BUCKET_NAME = "@@";
const s3 = new AWS.S3({ accessKeyId: ID, secretAccessKey: SECRET });
const params = {
  Bucket: BUCKET_NAME,
  CreateBucketConfiguration: {
    LocationConstraint: "ap-northeast-2",
  },
};

s3.createBucket(params, function (err, data) {
  if (err) {
    console.log(err, err.stack);
  } else {
    console.log("Bucket Created Successfully", data.Location);
  }
});

  • 버킷이 만들어짐을 확인할 수 있다.

📌버킷에 파일 업로드(Nodejs)

  • uploadFile.js
const fs = require("fs");
const AWS = require("aws-sdk");
const ID = "@@";
const SECRET = "@@";
const BUCKET_NAME = "testbucket00917";
const s3 = new AWS.S3({ accessKeyId: ID, secretAccessKey: SECRET });

const uploadFile = (fileName) => {
  const fileContent = fs.readFileSync(fileName);
  const params = {
    Bucket: BUCKET_NAME,
    Key: "test2.txt", // S3에 업로드 되었을 때 저장될 파일 이름
    Body: fileContent,
  };
  s3.upload(params, function (err, data) {
    if (err) {
      throw err;
    }
    console.log(`File uploaded successfully. ${data.Location}`);
  });
};

uploadFile("./test.txt");

  • test.txt 파일이 test2.txt 파일로 업로드 되었음을 확인할 수 있다.

📌버킷에서 파일 다운로드(Nodejs)

  • downloadFile.js
const fs = require("fs");
const AWS = require("aws-sdk");
const ID = "@@";
const SECRET = "@@";
const BUCKET_NAME = "testbucket00917";
const s3 = new AWS.S3({ accessKeyId: ID, secretAccessKey: SECRET });

const downloadFile = (fileName) => {
  const params = {
    Bucket: BUCKET_NAME,
    Key: "test2.txt", // 버켓에서 어떤 파일을 가져올 것인지
  };
  s3.getObject(params, function (err, data) {
    if (err) {
      throw err;
    }
    fs.writeFileSync(fileName, data.Body.toString());
  });
};

downloadFile("./test3.txt"); // parameter로 어떤 이름으로 local에 저장할 것인지

  • 버켓의 test2.txt 파일이 local의 test3.txt로 download 되었음을 확인할 수 있다.

📌공유, 권한

  • 객체의 링크를 통해 파일을 외부에 공유하고 싶다면, 객체의 권한을 설정해야 한다.
  • 객체를 클릭하고 권한 탭에서 퍼블릭 액세스의 객체 권한을 주면 된다 (읽기로)

📌스토리지 클래스

  • 스탠다드 : 제일 좋은 옵션
  • 스탠다드-IA : 자주 액세스 하지 않는 데이터(스탠다드보다 더 저렴)
  • 단일 영역-IA : 백업을 1개밖에 만들지 않으므로 자주 액세스하지도 않고 중요하지도 않은 데이터
  • 중복 감소 : 권장 X

  • 참고자료

https://stackabuse.com/uploading-files-to-aws-s3-with-node-js/
https://brunch.co.kr/@daniellim/43

  • 그 외 버킷과 관련된 다른 method ▼

https://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html


profile
Frontend Developer

0개의 댓글