

 [AWS SDK for JavaScript V3 API 참조 안내서](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)는 AWS SDK for JavaScript 버전 3(V3)의 모든 API 작업을 자세히 설명합니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Node.js 시작하기
<a name="getting-started-nodejs"></a>

이 안내서에서는 NPM 패키지를 초기화하고 패키지에 서비스 클라이언트를 추가하며 JavaScript SDK를 사용하여 서비스 작업을 직접적으로 호출하는 방법을 보여줍니다.

## 시나리오
<a name="getting-started-nodejs-scenario"></a>

**다음을 수행하는 하나의 기본 파일을 사용하여 새 NPM 패키지를 생성합니다.**
+ Amazon Simple Storage Service 버킷 생성
+ Amazon S3 버킷에 객체 배치
+ Amazon S3 버킷의 객체 읽기
+ 사용자가 리소스 삭제를 원하는지 확인

## 사전 조건
<a name="getting-started-nodejs-prerequisites"></a>

예를 실행하려면 먼저 다음을 수행해야 합니다.
+ SDK 인증을 구성합니다. 자세한 내용은 [를 사용한 SDK 인증 AWS](getting-your-credentials.md) 단원을 참조하십시오.
+ 개발을 위해 [Node.js](https://nodejs.org/en/download)의 활성 LTS 버전을 사용하여 Node.js. AWS recommends를 설치합니다.

## 1단계: 패키지 구조 설정 및 클라이언트 패키지 설치
<a name="getting-started-nodejs-setup-structure"></a>

패키지 구조를 설정하고 클라이언트 패키지를 설치하려면 다음을 수행합니다.

1. 패키지를 포함할 새 `nodegetstarted` 폴더를 생성합니다.

1. 명령줄에서 새 폴더로 이동합니다.

1. 다음 명령을 실행하여 기본 `package.json` 파일을 생성합니다.

   ```
   npm init -y
   ```

1. 다음 명령을 실행하여 Amazon S3 클라이언트 패키지를 설치합니다.

   ```
   npm i @aws-sdk/client-s3
   ```

1. `package.json` 파일에 `"type": "module"`을 추가합니다. 이렇게 하면 Node.js가 최신 ESM 구문을 사용하게 됩니다. 최종 `package.json`은 다음과 비슷해야 합니다.

   ```
   {
     "name": "example-javascriptv3-get-started-node",
     "version": "1.0.0",
     "description": "This guide shows you how to initialize an NPM package, add a service client to your package, and use the JavaScript SDK to call a service action.",
     "main": "index.js",
     "scripts": {
   "test": "vitest run **/*.unit.test.js"
     },
     "author": "Your Name",
     "license": "Apache-2.0",
     "dependencies": {
    "@aws-sdk/client-s3": "^3.420.0"
     },
     "type": "module"
   }
   ```

## 2단계: 필요한 가져오기 및 SDK 코드 추가
<a name="getting-started-with-node-js-add-code"></a>

`nodegetstarted` 폴더의 `index.js`라는 파일에 다음 코드를 추가합니다.

```
// This is used for getting user input.
import { createInterface } from "node:readline/promises";

import {
  S3Client,
  PutObjectCommand,
  CreateBucketCommand,
  DeleteObjectCommand,
  DeleteBucketCommand,
  paginateListObjectsV2,
  GetObjectCommand,
} from "@aws-sdk/client-s3";

export async function main() {
  // A region and credentials can be declared explicitly. For example
  // `new S3Client({ region: 'us-east-1', credentials: {...} })` would
  //initialize the client with those settings. However, the SDK will
  // use your local configuration and credentials if those properties
  // are not defined here.
  const s3Client = new S3Client({});

  // Create an Amazon S3 bucket. The epoch timestamp is appended
  // to the name to make it unique.
  const bucketName = `test-bucket-${Date.now()}`;
  await s3Client.send(
    new CreateBucketCommand({
      Bucket: bucketName,
    }),
  );

  // Put an object into an Amazon S3 bucket.
  await s3Client.send(
    new PutObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
      Body: "Hello JavaScript SDK!",
    }),
  );

  // Read the object.
  const { Body } = await s3Client.send(
    new GetObjectCommand({
      Bucket: bucketName,
      Key: "my-first-object.txt",
    }),
  );

  console.log(await Body.transformToString());

  // Confirm resource deletion.
  const prompt = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  const result = await prompt.question("Empty and delete bucket? (y/n) ");
  prompt.close();

  if (result === "y") {
    // Create an async iterator over lists of objects in a bucket.
    const paginator = paginateListObjectsV2(
      { client: s3Client },
      { Bucket: bucketName },
    );
    for await (const page of paginator) {
      const objects = page.Contents;
      if (objects) {
        // For every object in each page, delete it.
        for (const object of objects) {
          await s3Client.send(
            new DeleteObjectCommand({ Bucket: bucketName, Key: object.Key }),
          );
        }
      }
    }

    // Once all the objects are gone, the bucket can be deleted.
    await s3Client.send(new DeleteBucketCommand({ Bucket: bucketName }));
  }
}

// Call a function if this file was run directly. This allows the file
// to be runnable without running on import.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```

코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/nodegetstarted/index.js) 찾을 수 있습니다.

## 3단계: 예시 실행
<a name="getting-started-with-node-js-run"></a>

**참고**  
로그인하는 것을 잊지 마세요\$1 IAM Identity Center를 사용하여 인증하는 경우 명령을 사용하여 AWS CLI `aws sso login` 로그인해야 합니다.

1. `node index.js`를 실행합니다.

1. 버킷을 비우고 삭제할지 여부를 선택합니다.

1. 버킷을 삭제하지 않는 경우 나중에 수동으로 비우고 삭제해야 합니다.