728x90
aws-sdk 를 이용하여 AWS S3 를 다뤄보자. (S3 참고글은 [S3] AWS S3 버킷 만들기)
AWS SDK - S3
aws-sdk 설치하기
$ npm install aws-sdk
▷ lib/s3.js
1. AWS config 세팅하기
const AWS = require('aws-sdk')
const AWS_region = process.env.AWS_REGION || 'ap-northeast-2'
const s3 = new AWS.S3({
region: AWS_region,
})
[putObject]
module.exports.putObject = (bucketName, bucketKey) => async (fileName, data) => {
const params = {
Bucket: bucketName,
}
if (bucketKey) params.Key = bucketKey
if (fileName) params.Key = fileName
if (bucketKey && fileName) params.Key = `${bucketKey}${fileName}`
if (data) params.Body = Buffer.from(data)
return await s3
.putObject(params)
.promise()
.then((res) => console.log(res))
}
[upload]
module.exports.upload = (bucketName, bucketKey) => async (fileName, data) => {
const params = {
Bucket: bucketName,
}
if (bucketKey) params.Key = bucketKey
if (fileName) params.Key = fileName
if (bucketKey && fileName) params.Key = `${bucketKey}${fileName}`
if (data) params.Body = Buffer.from(data)
return await s3
.upload(params)
.promise()
.then((res) => console.log(res))
}
[listObjects]
module.exports.listObjects = (bucketName, bucketKey) => async () => {
const params = {
Bucket: bucketName,
}
if (bucketKey) params.Prefix = bucketKey
return await s3.listObjects(params).promise()
}
▷ index.js
[putObject] Example#1
const { putObject, upload } = require('./lib/s3')
;(async () => {
const bucketName = `yonikim-bucket`
const bucketKey = `test/`
await putObject(bucketName, bucketKey)()
})()
AWS S3 > yonikim-bucket > test 폴더가 생긴다.
[putObject] Example#2
const { putObject, upload } = require('./lib/s3')
;(async () => {
const bucketName = `yonikim-bucket`
// const bucketKey = `test/`
const fileName = 'test2.txt'
const data = 'Hello, YONIKIM WORLD'
await putObject(bucketName)(fileName, data)
})()
AWS S3 > yonikim-bucket > test2.txt 파일이 생긴다.
[upload] Example#1
const { putObject, upload } = require('./lib/s3')
;(async () => {
const bucketName = `yonikim-bucket`
const bucketKey = `test/`
const fileName = 'test.txt'
const data = 'Hello, YONIKIM WORLD'
await upload(bucketName, bucketKey)(fileName, data)
})()
AWS S3 > yonikim-bucket > test > test.txt 파일이 생긴다.
[다운로드] 받아서 확인해 보면 data 가 잘 출력되는 걸 확인할 수 있다.
[listObjects] Example#1
const { putObject, upload, listObjects } = require('./lib/s3')
;(async () => {
const bucketName = `yonikim-bucket`
const bucketKey = `test/`
const s3List = await listObjects(bucketName)()
console.log(s3List)
})()
[listObjects] Example#2
const { putObject, upload, listObjects } = require('./lib/s3')
;(async () => {
const bucketName = `yonikim-bucket`
const bucketKey = `test/`
const s3List = await listObjects(bucketName, bucketKey)()
console.log(s3List)
})()
728x90
'Node.js' 카테고리의 다른 글
[ECMAScript] ES6 이후의 변경점 (0) | 2021.09.17 |
---|---|
[Node.js] 가상화폐 매매 API 만들기 - 1. 세팅하기 (0) | 2021.07.26 |
[Node.js] 원하는 길이만큼 유니크 아이디 만들기 (0) | 2021.05.27 |
[Node.js] AWS SDK - DynamoDB (0) | 2021.05.26 |
[Node.js] XLSX 파일 JSON 파일로 만들기 (0) | 2021.05.26 |