투케이2K

464. (javaScript) 자바스크립트 S3 특정 버킷 (Bucket) 에 저장 된 파일 전체 목록 조회 - NextContinuationToken, ListObjectsV2 본문

JavaScript

464. (javaScript) 자바스크립트 S3 특정 버킷 (Bucket) 에 저장 된 파일 전체 목록 조회 - NextContinuationToken, ListObjectsV2

투케이2K 2025. 12. 8. 20:03
728x90
반응형

[개발 환경 설정]

개발 툴 : Edit++

개발 언어 : JavaScript

 

[소스 코드]

-----------------------------------------------------------------------------------------
[사전 설명 및 설정 사항]
-----------------------------------------------------------------------------------------

- 개발 환경 : Web


- 개발 기술 : JavaScript (자바스크립트) / AWS / S3 / Bucket


- 사전) Aws S3 버킷 저장소 간략 설명 : 

  >> AWS S3 버킷 이란 데이터 (사진, 동영상, 문서 등) 객체 를 업로드할 수 있는 컨테이너 (디렉토리) 입니다

  >> AWS S3 구현 측면에서 버킷과 객체는 AWS 리소스에 해당되며 Amazon S3는 이를 관리하기 위한 API를 제공합니다
  
    - Amazon S3 API를 사용하여 버킷을 만들고 객체를 업로드할 수 있습니다
  
    - Amazon S3 콘솔을 사용하여 수행할 수도 있습니다

  >> AWS S3 버킷이 생성된 후에는 해당 버킷이 삭제될 때까지 동일한 파티션의 다른 AWS 계정이 해당 버킷 이름을 사용할 수 없습니다

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[소스 코드]
-----------------------------------------------------------------------------------------

<!DOCTYPE HTML>
<html lang="ko">
<head>
    <title>javaScriptTest</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">


    <!-- 반응형 구조 만들기 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">


    <!-- 내부 CSS 스타일 지정 -->
    <style>

        html, body {
            width: 100%;
            height: 100%;
            margin : 0 auto;
            padding : 0;
            border : none;
            background-color: #666;
        }

    </style>





    <!-- [CDN 주소 설정] -->
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1416.0.min.js"></script>






    <!-- [자바스크립트 코드 지정] -->
    <script>

        // --------------------------------------------------------------------------------------------------------------

        // [전역 변수 선언]
        const region = 'ap-northeast-2'; // [AWS 리전]
        const accessKeyId = 'AK..7Q'; // [IAM 액세스 키]
        const secretAccessKey = 'Zz..xj'; // [IAM 시크릿 키]

        const bucketName = 'service'; // [S3 버킷 명칭]

        // [내부 클로저 선언 실시]
        var innerFunction = null;

        // [조회 된 정보를 담을 배열 선언]
        const bucketAllList = [];

        // [반복 조회를 위한 continueToken 변수 선언]
        var continueToken = null;

        // --------------------------------------------------------------------------------------------------------------

        // [html 최초 로드 및 이벤트 상시 대기 실시]
        window.onload = async function() {
            console.log("");
            console.log("=========================================");
            console.log("[window onload] : [start]");
            console.log("=========================================");
            console.log("");


            // -----------------------------------------
            // [초기 변수 초기화]
            // -----------------------------------------
            innerFunction = null;
            bucketAllList.length = 0;
            continueToken = null;


            // -----------------------------------------
            // [AWS.config 지정]
            // -----------------------------------------
            // IAM 계정 정보를 사용해 AWS.config 정보 업데이트 수행
            // -----------------------------------------            
            AWS.config.update({
              region: region,
              accessKeyId: accessKeyId,
              secretAccessKey: secretAccessKey
            });



            // -----------------------------------------
            // [AWS.S3 객체 생성]
            // -----------------------------------------
            const aws = new AWS.S3();


            // -----------------------------------------
            // [내부 클로저 함수 정의]
            // -----------------------------------------
            innerFunction = async function() {

              try {
                
                while (true) { // 반복 조회 수행

                  // -----------------------------------------
                  // [요청 파라미터 생성]
                  // -----------------------------------------
                  var param = null;

                  if (continueToken != null && continueToken != undefined && continueToken != ''){
                    param = {
                      Bucket: bucketName, // 버킷 이름
                      Prefix: '', // 특정 폴더만 보고 싶다면 'folder-name/' 입력
                      MaxKeys: 100, // 페이지 당 조회 Key 개수
                      ContinuationToken : continueToken // ✅ 반복 조회 토큰 지정
                    };
                  }
                  else {
                    param = {
                      Bucket: bucketName, // 버킷 이름
                      Prefix: '', // 특정 폴더만 보고 싶다면 'folder-name/' 입력
                      MaxKeys: 100 // 페이지 당 조회 Key 개수
                    };

                  }


                  // -----------------------------------------
                  // [listObjectsV2 버킷에 저장된 객체 반환 수행]
                  // -----------------------------------------

                  // AWS 참고 사이트 : https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
                  // -----------------------------------------
                  const [s3_err, s3_res] = await aws.listObjectsV2( param ).promise()                
                    .then(data => [null, data])
                    .catch(error => [error, null]);

                  if (s3_err) {
                    console.error("");
                    console.error("=========================================");
                    console.error("[listObjectsV2] : [Error]");
                    console.error("---------------------------------------");
                    console.error(s3_err);					
                    console.error("=========================================");
                    console.error("");

                    // [반복 조회 종료 위한 값 초기화]
                    continueToken = null;

                  } else {
                    console.log("");
                    console.log("=========================================");
                    console.log("[listObjectsV2] : [Success]");
                    console.log("---------------------------------------");
                    console.log(JSON.stringify(s3_res));
                    console.log("=========================================");
                    console.log("");

                    // ---------------------------------------------
                    // ✅ [로그 출력 예시 첨부]
                    // ---------------------------------------------
                    /*
                    {
                      "IsTruncated": false,
                      "Contents": [
                        {
                          "Key": "app/test_B20251118.apk",
                          "LastModified": "2025-11-18T02:24:02.000Z",
                          "ETag": "\"5525..e5-3\"",
                          "ChecksumAlgorithm": [
                            "CRC64NVME"
                          ],
                          "Size": 37080953,
                          "StorageClass": "STANDARD"
                        }
                      ],
                      "Name": "service",
                      "Prefix": "",
                      "MaxKeys": 20,
                      "CommonPrefixes": [],
                      "KeyCount": 11,
                      "ContinuationToken": "1LUu6OIrl..PqGh"
                    }
                    */              
                    // ---------------------------------------------


                    // ---------------------------------------------
                    // [배열에 전체 리스트 정보 추가]
                    // ---------------------------------------------
                    const resContentList = s3_res.Contents;

                    if (resContentList != null && resContentList != undefined){
                      bucketAllList.push(...resContentList); // ✅ Array Add List
                    }
                    

                    // ---------------------------------------------
                    // [반복 조회에 사용 될 NextContinuationToken 정보가 있는지 확인]
                    // ---------------------------------------------
                    const resNextContinuationToken = s3_res.NextContinuationToken;
                    if (s3_res.IsTruncated && resNextContinuationToken != null && resNextContinuationToken != undefined && resNextContinuationToken != ''){
                      continueToken = resNextContinuationToken; // ✅ Set NextContinuationToken
                    }
                    else {
                      continueToken = null; // Clear NextContinuationToken
                    }

                  }


                  // ---------------------------------------------
                  // [반복 조회에 사용 될 continueToken 정보가 있는지 확인 후 무한 루프 탈출 수행]
                  // ---------------------------------------------
                  if (continueToken == null || continueToken == undefined || continueToken == ''){
                    console.error("[innerFunction] : [continueToken] : Is Null >> Stop While True");
                    break;
                  }
                  else {
                    console.warn("[innerFunction] : [continueToken] : Exists >> Go To While True");
                  }

                }


                console.log("");
                console.log("=========================================");
                console.log("[innerFunction] : [bucketAllList] : Result");
                console.log("---------------------------------------");
                console.log("Length : ", bucketAllList.length);
                console.log("---------------------------------------");
                console.log(JSON.stringify(bucketAllList));
                console.log("=========================================");
                console.log("");

              }
              catch(exception){
                console.error("");
                console.error("=========================================");
                console.error("[innerFunction] : [Exception] : ", exception);
                console.error("=========================================");
                console.error("");
              }

            };



            // -----------------------------------------
            // [내부 클로저 함수 호출]
            // -----------------------------------------
            innerFunction();

        };

        // --------------------------------------------------------------------------------------------------------------

    </script>


</head>


<body>

</body>

</html>

-----------------------------------------------------------------------------------------





-----------------------------------------------------------------------------------------
[참고 사이트]
-----------------------------------------------------------------------------------------

[IT 기술] AWS S3 버킷 저장소 설명

https://kkh0977.tistory.com/4468

https://blog.naver.com/kkh0977/223173146602?trackingCode=blog_bloghome_searchlist


[자바스크립트 AWS S3 listObjectsV2 버킷에 생성 객체 목록 리스트 조회 수행]

https://blog.naver.com/kkh0977/223902546491


[Web/JavaScript] AWS STS 임시 자격 증명 사용해 S3 파일 다운로드 Get Pre-SignedUrl 확인 수행

https://blog.naver.com/kkh0977/224007760700?trackingCode=blog_bloghome_searchlist


[간단 소스] Aws S3 버킷 저장소 리스트 목록 확인 - AmazonS3 listBuckets

https://blog.naver.com/kkh0977/223797258160?trackingCode=blog_bloghome_searchlist

-----------------------------------------------------------------------------------------
 
728x90
반응형
Comments