S3를 사용하던 예전에 짠 소스를 수정할 일이 생겨서 정리하게 되었다.
const { S3Client, ListObjectsV2Command } = require('@aws-sdk/client-s3');
// 설정란
const accessKeyId = "<accessKeyId>";
const secretAccessKey = "<secretAccessKey>";
const region = "<region>";
const Bucket = "<BucketName>";
const Prefix = "<Path>";
const s3Client = new S3Client({ region, credentials: { accessKeyId, secretAccessKey } });
const listObjectsCommand = new ListObjectsV2Command({ Bucket, Prefix });
s3Client.send(listObjectsCommand)
.then((response) => {
for(let i=1; i<response.Contents.length; i++){
key = response.Contents[i].Key;
}
})
.catch((error) => {
res.send(error);
});
위 소스를 해석해보자면 S3에 접근하기 위해서 필요한 데이터는 아래와 같이 5개가 필요하다.
- 접근키 accessKeyId
- 암호키 secretAccessKey
- 지역 region
- 버킷네임 Bucket
- 가져올 경로 Prefix
위 소스에서는 경로내의 모든 파일을 조회해서 데이터를 for문으로 받아왔는데, 필요한 데이터 하나만 가져올수도 있다.
Key 뿐만 아니라 아래와 같은 데이터 포맷으로 넘어온다.