Javascript SDK
    • PDF

    Javascript SDK

    • PDF

    기사 요약

    Classic/VPC 환경에서 이용 가능합니다.

    Javascript SDK for S3 API

    AWS S3에서 제공하는 Javascript SDK를 이용하여 네이버 클라우드 플랫폼 Object Storage를 사용하는 방법을 설명합니다.

    이 문서는 AWS Javascript SDK 2.348.0 버전을 기준으로 작성되었습니다.

    설치

    npm install --save aws-sdk@2.348.0
    

    AWS Javascript SDK

    예제

    예제에서 사용하는 access_key, secret_key는 등록한 API 인증키 정보로 입력해야 합니다.

    버킷 생성

    const AWS = require('aws-sdk');
    
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    const S3 = new AWS.S3({
        endpoint,
        region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    
    const bucket_name = 'sample-bucket';
    
    
    (async () => {
    
        await S3.createBucket({
            Bucket: bucket_name,
            CreateBucketConfiguration: {}
        }).promise()
    
    })();
    

    버킷 목록 조회

    const AWS = require('aws-sdk');
    
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    (async () => {
    
        let { Buckets } = await S3.listBuckets().promise();
    
        for(let bucket of Buckets) {
            console.log(bucket.Name);
        }
    
    })();
    

    버킷 삭제

    const AWS = require('aws-sdk');
    
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    
    
    const bucket_name = 'sample-bucket';
    
    (async () => {
    
        await S3.deleteBucket({
            Bucket: bucket_name
        }).promise();
    
    })();
    

    오브젝트 업로드

    const AWS = require('aws-sdk');
    const fs = require('fs');
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    
    const bucket_name = 'sample-bucket';
    const local_file_path = '/tmp/test.txt';
    
    
    
    (async () => {
    
        let object_name = 'sample-folder/';
        // create folder
        await S3.putObject({
            Bucket: bucket_name,
            Key: object_name
        }).promise();
    
        object_name = 'sample-object';
    
        // upload file
        await S3.putObject({
            Bucket: bucket_name,
            Key: object_name,
            ACL: 'public-read',
            // ACL을 지우면 전체공개가 되지 않습니다.
            Body: fs.createReadStream(local_file_path)
        }).promise();
    
    })();
    
    

    오브젝트 목록 조회

    const AWS = require('aws-sdk');
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    const bucket_name = 'sample-bucket';
    const MAX_KEYS = 300;
    
    var params = {
        Bucket: bucket_name,
        MaxKeys: MAX_KEYS,
        FetchOwner: true
    };
    
    (async () => {
    
        // List All Objects
        console.log("List All In The Bucket");
        console.log("==========================");
    
        while (true) {
        
            let response = await S3.listObjectsV2(params).promise();
    
            console.log(`IsTruncated = ${response.IsTruncated}`);
            console.log(
                `ContinuationToken = ${response.ContinuationToken ? response.ContinuationToken : null}`
            );
            console.log(
                `NextContinuationToken = ${
                    response.NextContinuationToken ? response.NextContinuationToken : null
                }`
            );
            console.log(`  Object Lists`);
            for (let content of response.Contents) {
                console.log(
                    `    Name = ${content.Key}, Size = ${content.Size}, Owner = ${content.Owner.ID}`
                );
            }
    
            if (response.IsTruncated) {
                params.ContinuationToken = response.NextContinuationToken;
            } else {
                break;
            }
            
        }
    
        // List Top Level Folder And Files
        params.Delimiter = "/";
        console.log("Top Level Folders And Files In The Bucket");
        console.log("==========================");
    
        while (true) {
        
            let response = await S3.listObjectsV2(params).promise();
    
            console.log(`IsTruncated = ${response.IsTruncated}`);
            console.log(
                `ContinuationToken = ${response.ContinuationToken ? response.ContinuationToken : null}`
            );
            console.log(
                `NextContinuationToken = ${
                    response.NextContinuationToken ? response.NextContinuationToken : null
                }`
            );
    
            console.log(`  Folder Lists`);
            for (let folder of response.CommonPrefixes) {
                console.log(`    Name = ${folder.Prefix}`);
            }
    
            console.log(`  File Lists`);
            for (let content of response.Contents) {
                console.log(
                    `    Name = ${content.Key}, Size = ${content.Size}, Owner = ${content.Owner.ID}`
                );
            }
    
            if (response.IsTruncated) {
                params.ContinuationToken = response.NextContinuationToken;
            } else {
                break;
            }
        }
        
    })();
    

    오브젝트 다운로드

    const AWS = require('aws-sdk');
    const fs = require('fs');
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    const bucket_name = 'sample-bucket';
    const object_name = 'sample-object';
    const local_file_path = '/tmp/test.txt';
    
    
    (() => {
    
        let outStream = fs.createWriteStream(local_file_path);
        let inStream = S3.getObject({
            Bucket: bucket_name,
            Key: object_name
        }).createReadStream();
    
        inStream.pipe(outStream);
        inStream.on('end', () => {
            console.log("Download Done");
        });
    
    })();
    

    오브젝트 삭제

    const AWS = require('aws-sdk');
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    const bucket_name = 'sample-bucket';
    
    (async () => {
    
        // Delete Folder
        let object_name = 'sample-folder/';
    
        await S3.deleteObject({
            Bucket: bucket_name,
            Key: object_name
        }).promise();
    
        // Delete File
        object_name = 'sample-object';
    
        await S3.deleteObject({
            Bucket: bucket_name,
            Key: object_name
        }).promise();
    
    })();
    

    ACL 설정

    const AWS = require('aws-sdk');
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    const bucket_name = 'sample-bucket'
    const object_name = 'sample-object'
    const owner_id = 'test-owner-id'
    const target_id = 'test-user-id'
    
    (async () => {
    
        await S3.putObjectAcl({
            Bucket: bucket_name,
            Key: object_name,
            AccessControlPolicy: {
                'Grants': [
                    {
                        'Grantee': {
                            'ID': owner_id,
                            'Type': 'CanonicalUser'
                        },
                        'Permission': 'FULL_CONTROL'
                    },
                    {
                        'Grantee': {
                            'ID': target_id,
                            'Type': 'CanonicalUser'
                        },
                        'Permission': 'READ'
                    }
                ],
                'Owner': {
                    'ID': owner_id
                }
            }
        }).promise();
    
    })();
    

    멀티 파트 업로드

    주의

    멀티 파트 업로드를 완료하지 않을 경우 잔여 파일이 버킷에 남게 되며, 잔여 파일은 버킷 용량에 포함되어 과금됩니다.
    아래 방법을 통해 불완전한 멀티파트 객체를 삭제하여 불필요한 과금이 되지 않도록 주의하시기 바랍니다.

    1. 취소 또는 완료되지 않은 멀티파트 업로드 정보 조회: ListMultipartUploads API 가이드 참고
    2. 멀티 파트 삭제: AbortMultipartUpload API 가이드 참고
    const AWS = require('aws-sdk');
    const fs = require('fs');
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = 'ACCESS_KEY';
    const secret_key = 'SECRET_KEY';
    
    const S3 = new AWS.S3({
        endpoint: endpoint,
        region: region,
        credentials: {
            accessKeyId : access_key,
            secretAccessKey: secret_key
        }
    });
    
    const bucket_name = 'sample-bucket';
    const local_file_name = '/tmp/sample.file';
    const object_name = 'sample-large-object';
    
    let options = {
        partSize: 5 * 1024 * 1024
    };
    
    
    (async () => {
    
        await S3.upload({
            Bucket: bucket_name,
            Key: object_name,
            Body: fs.createReadStream(local_file_name)
        }, options).promise();
    
    })();
    

    CORS(Cross-Origin Resource Sharing) 설정

    const AWS = require('aws-sdk');
    
    const endpoint = new AWS.Endpoint('https://kr.object.gov-ncloudstorage.com');
    const region = 'gov-standard';
    const access_key = '<ACCESS_KEY>';
    const secret_key = '<SECRET_KEY>';
    
    const S3 = new AWS.S3({
      endpoint,
      region,
      credentials: {
        accessKeyId: access_key,
        secretAccessKey: secret_key,
      },
    });
    
    const bucket_name = 'sample-bucket';
    
    const params = {
      Bucket: bucket_name,
      CORSConfiguration: {
        CORSRules: [
          {
            AllowedHeaders: ["*"],
            AllowedMethods: ["GET", "PUT"],
            AllowedOrigins: ["*"],
            MaxAgeSeconds: 3000,
          },
        ],
      },
    };
    
    (async () => {
    // Set CORS
      await S3.putBucketCors(params).promise();
      
    // Get CORS
      const response = await S3.getBucketCors({ Bucket: bucket_name }).promise();
      console.log(JSON.stringify(response, null, 2));
    })();
    

    이 문서가 도움이 되었습니까?

    What's Next
    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.