티스토리 뷰

1. nodejs에서 aws-sdk 사용하기      

# 프로젝트 초기화
$> npm init # aws-sdk 모듈 설치
$> npm install aws-sdk --save 

 

2. bucket 생성 하기

createBucket.js      

const AWS = require('aws-sdk');
const ID = 'Access key Id';
const SECRET = '';
const BUCKET_NAME = '';
const s3 = new AWS.S3({   accessKeyId: ID,   secretAccessKey: SECRET });
const params = {
   Bucket: BUCKET_NAME,
   CreateBucketConfiguration: {
       // Set your region here
       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);
 }); 

 

3. 파일 업로드

uploadFile.js      

const fs = require('fs');
const AWS = require('aws-sdk');
const BUCKET_NAME = '';
const s3 = new AWS.S3({   accessKeyId: '',   secretAccessKey: '' });
const uploadFile = (fileName) => {
   const fileContent = fs.readFileSync(fileName);
   const params = {
       Bucket: BUCKET_NAME,
       Key: 'test.txt', // File name you want to save as in S3
       Body: fileContent   }
;
   s3.upload(params, function(err, data) {
       if (err) { throw err; }
      console.log(`File uploaded successfully. ${data.Location}`);
   });
 };
uploadFile('./uploads/test.txt'); 

 

4. 파일 다운로드

download.js      

const fs = require('fs');
const AWS = require('aws-sdk');
 const BUCKET_NAME = '';
const s3 = new AWS.S3({   accessKeyId: '',   secretAccessKey: '' });
const downloadFile = (fileName) => {   
  const params = {       
    Bucket: BUCKET_NAME,      
    Key: 'test.txt', // File name you want to save as in S3   
  };   
    s3.getObject(params, function(err, data) {       
      if (err) {           
          throw err;      
      }
      fs.writeFileSync(fileName, data.Body.toString());  
     });
};
downloadFile('../../uploads/test-download.txt'); 

 

댓글