

AWS SDK for JavaScript v2가 지원 종료에 도달했습니다. [AWS SDK for JavaScript v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/)로 마이그레이션하실 것을 권장합니다. 마이그레이션 방법에 대한 자세한 내용은 해당 [공지 사항](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)을 참조하세요.

# SDK for JavaScript 코드 예제
<a name="sdk-code-samples"></a>

이 단원의 주제에는 다양한 서비스의 API와 함께 AWS SDK for JavaScript를 사용하여 일반적인 작업을 수행하는 방법을 보여 주는 예제가 포함됩니다.

GitHub의 AWS 설명서 [코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples)에서 이러한 예제의 소스 코드와 다른 코드를 찾습니다. AWS 설명서 팀이 생성을 고려할 수 있는 새 코드 예제를 제안하려면 새 요청을 생성합니다. 이 팀은 개별 API 호출만 다루는 간단한 코드 조각에 비해 광범위한 시나리오 및 사용 사례를 다루는 코드를 생성하려고 합니다. 지침은 [배포 가이드라인](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/CONTRIBUTING.md#authoring-code)의 *코드 작성* 섹션을 참조하세요.

**Topics**
+ [Amazon CloudWatch 예제](cloudwatch-examples.md)
+ [Amazon DynamoDB 예제](dynamodb-examples.md)
+ [Amazon EC2 예제](ec2-examples.md)
+ [AWS Elemental MediaConvert 예제](emc-examples.md)
+ [AWS IAM 예제](iam-examples.md)
+ [Amazon Kinesis 예제](kinesis-examples.md)
+ [Amazon S3 예제](s3-examples.md)
+ [Amazon Simple Email Services 예제](ses-examples.md)
+ [Amazon Simple Notification Service 예](sns-examples.md)
+ [Amazon SQS 예제](sqs-examples.md)

# Amazon CloudWatch 예제
<a name="cloudwatch-examples"></a>

Amazon CloudWatch(CloudWatch)는 Amazon Web Services 리소스 및 AWS에서 실행되는 애플리케이션을 실시간으로 모니터링하는 웹 서비스입니다. CloudWatch를 사용하여 리소스 및 애플리케이션에 대해 측정할 수 있는 변수인 지표를 수집하고 추적할 수 있습니다. CloudWatch 경보는 알림을 보내거나 정의한 규칙을 기준으로 모니터링하는 리소스를 자동으로 변경합니다.

![\[JavaScript 환경, SDK, CloudWatch 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-cloudwatch.png)


CloudWatch용 JavaScript API는 `AWS.CloudWatch`, `AWS.CloudWatchEvents`, `AWS.CloudWatchLogs` 클라이언트 클래스를 통해 노출됩니다. CloudWatch 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html), [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html), [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html) 섹션을 참조하세요.

**Topics**
+ [Amazon CloudWatch 경보 생성](cloudwatch-examples-creating-alarms.md)
+ [Amazon CloudWatch 경보 작업 사용](cloudwatch-examples-using-alarm-actions.md)
+ [Amazon CloudWatch에서 지표 가져오기](cloudwatch-examples-getting-metrics.md)
+ [Amazon CloudWatch Events에 이벤트 전송](cloudwatch-examples-sending-events.md)
+ [Amazon CloudWatch Logs 구독 필터 사용](cloudwatch-examples-subscriptions.md)

# Amazon CloudWatch 경보 생성
<a name="cloudwatch-examples-creating-alarms"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ CloudWatch 경보에 대한 기본 정보를 가져오는 방법
+ CloudWatch 경보를 생성하고 삭제하는 방법

## 시나리오
<a name="cloudwatch-examples-creating-alarms-scenario"></a>

경보는 지정한 기간에 단일 지표를 감시하고 여러 기간에 지정된 임곗값에 대한 지표 값을 기준으로 작업을 하나 이상 수행합니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 CloudWatch에서 경보를 생성합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.CloudWatch` 클라이언트 클래스의 다음 메서드를 사용하여 알람을 생성합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#describeAlarms-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#describeAlarms-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#putMetricAlarm-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#putMetricAlarm-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#deleteAlarms-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#deleteAlarms-property)

CloudWatch 경보에 대한 자세한 내용은 *Amazon CloudWatch 사용 설명서*의 [Amazon CloudWatch 경보 생성](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)을 참조하세요.

## 사전 필수 작업
<a name="cloudwatch-examples-creating-alarms-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 경보 설명
<a name="cloudwatch-examples-creating-alarms-describing"></a>

파일 이름이 `cw_describealarms.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch에 액세스하려면 `AWS.CloudWatch` 서비스 객체를 생성합니다. 경보 설명을 가져오기 위한 파라미터를 담을 JSON 객체를 생성하여 `INSUFFICIENT_DATA` 상태의 설명으로 반환되는 경보를 제한합니다. 그런 다음 `describeAlarms` 서비스 객체의 `AWS.CloudWatch` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

cw.describeAlarms({ StateValue: "INSUFFICIENT_DATA" }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    // List the names of all current alarms in the console
    data.MetricAlarms.forEach(function (item, index, array) {
      console.log(item.AlarmName);
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cw_describealarms.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/cloudwatch/cw_describealarms.js)에서 찾을 수 있습니다.

## CloudWatch 지표에 대한 경보 생성
<a name="cloudwatch-examples-creating-alarms-putmetricalarm"></a>

파일 이름이 `cw_putmetricalarm.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch에 액세스하려면 `AWS.CloudWatch` 서비스 객체를 생성합니다. 지표(이 경우 Amazon EC2 인스턴스의 CPU 사용률)를 기반으로 경보를 생성하는 데 필요한 파라미터를 담을 JSON 객체를 생성합니다. 나머지 파라미터는 지표가 임계값인 70퍼센트를 초과할 때 경보가 트리거되도록 설정됩니다. 그런 다음 `describeAlarms` 서비스 객체의 `AWS.CloudWatch` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  AlarmName: "Web_Server_CPU_Utilization",
  ComparisonOperator: "GreaterThanThreshold",
  EvaluationPeriods: 1,
  MetricName: "CPUUtilization",
  Namespace: "AWS/EC2",
  Period: 60,
  Statistic: "Average",
  Threshold: 70.0,
  ActionsEnabled: false,
  AlarmDescription: "Alarm when server CPU exceeds 70%",
  Dimensions: [
    {
      Name: "InstanceId",
      Value: "INSTANCE_ID",
    },
  ],
  Unit: "Percent",
};

cw.putMetricAlarm(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cw_putmetricalarm.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/cloudwatch/cw_putmetricalarm.js)에서 찾을 수 있습니다.

## 경보 삭제
<a name="cloudwatch-examples-creating-alarms-deleting"></a>

파일 이름이 `cw_deletealarms.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch에 액세스하려면 `AWS.CloudWatch` 서비스 객체를 생성합니다. 삭제할 경보의 이름을 담을 JSON 객체를 생성합니다. 그런 다음 `deleteAlarms` 서비스 객체의 `AWS.CloudWatch` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  AlarmNames: ["Web_Server_CPU_Utilization"],
};

cw.deleteAlarms(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cw_deletealarms.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/cloudwatch/cw_deletealarms.js)에서 찾을 수 있습니다.

# Amazon CloudWatch 경보 작업 사용
<a name="cloudwatch-examples-using-alarm-actions"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ CloudWatch 경보를 기반으로 Amazon EC2 인스턴스의 상태를 자동으로 변경하는 방법

## 시나리오
<a name="cloudwatch-examples-using-alarm-actions-scenario"></a>

경보 작업을 사용하면 Amazon EC2 인스턴스를 자동으로 중지, 종료, 재부팅 또는 복구하는 경보를 만들 수 있습니다. 인스턴스를 더는 실행할 필요가 없을 때 중지 또는 종료 작업을 사용할 수 있습니다. 재부팅 및 복구 작업을 사용하여 인스턴스를 자동으로 재부팅할 수 있습니다.

이 예제에서는 Amazon EC2 인스턴스의 재부팅을 트리거하는 CloudWatch의 경보 작업을 정의하는 데 일련의 Node.js 모듈이 사용됩니다. Node.js 모듈은 SDK for JavaScript로 `CloudWatch` 클라이언트 클래스의 다음 메서드를 사용하여 Amazon EC2 인스턴스를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#enableAlarmActions-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#enableAlarmActions-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#disableAlarmActions-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#disableAlarmActions-property)

CloudWatch 경보 작업에 대한 자세한 내용을 알아보려면 *Amazon CloudWatch 사용 설명서*의 [인스턴스를 중지, 종료, 재부팅 또는 복구하는 경보 생성](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingAlarmActions.html)을 참조하세요.

## 사전 필수 작업
<a name="cloudwatch-examples-using-alarm-actions-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](http://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ Amazon EC2 인스턴스를 설명, 재부팅, 중지 또는 종료할 권한을 부여하는 정책이 있는 IAM 역할을 생성합니다. IAM 역할 생성에 관한 자세한 내용은 *IAM 사용 설명서*의 [AWS 서비스에 대한 권한을 위임할 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) 섹션을 참조하세요.

IAM 역할을 생성할 때 다음 역할 정책을 사용합니다.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Action": [
            "cloudwatch:Describe*",
            "ec2:Describe*",
            "ec2:RebootInstances",
            "ec2:StopInstances*",
            "ec2:TerminateInstances"
         ],
         "Resource": [
            "*"
         ]
      }
   ]
}
```

------

## 
<a name="cloudwatch-examples-using-alarm-actions-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 경보 작업 생성 및 활성화
<a name="cloudwatch-examples-using-alarm-actions-enabling"></a>

파일 이름이 `cw_enablealarmactions.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch에 액세스하려면 `AWS.CloudWatch` 서비스 객체를 생성합니다.

경보를 생성하기 위한 파라미터를 담을 JSON 객체를 생성하여 `ActionsEnabled`를 `true`로 지정하고 경보가 트리거할 작업에 대한 ARN 배열을 지정합니다. 경보가 없으면 생성하거나 경보가 있으면 업데이트하는 `putMetricAlarm` 서비스 객체의 `AWS.CloudWatch` 메서드를 호출합니다.

`putMetricAlarm`에 대한 콜백 함수가 성공적으로 완료되면 CloudWatch 경보의 이름이 포함된 JSON 객체를 생성합니다. `enableAlarmActions` 메서드를 호출하여 경보 작업을 활성화합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  AlarmName: "Web_Server_CPU_Utilization",
  ComparisonOperator: "GreaterThanThreshold",
  EvaluationPeriods: 1,
  MetricName: "CPUUtilization",
  Namespace: "AWS/EC2",
  Period: 60,
  Statistic: "Average",
  Threshold: 70.0,
  ActionsEnabled: true,
  AlarmActions: ["ACTION_ARN"],
  AlarmDescription: "Alarm when server CPU exceeds 70%",
  Dimensions: [
    {
      Name: "InstanceId",
      Value: "INSTANCE_ID",
    },
  ],
  Unit: "Percent",
};

cw.putMetricAlarm(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Alarm action added", data);
    var paramsEnableAlarmAction = {
      AlarmNames: [params.AlarmName],
    };
    cw.enableAlarmActions(paramsEnableAlarmAction, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Alarm action enabled", data);
      }
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cw_enablealarmactions.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/cloudwatch/cw_enablealarmactions.js)에서 찾을 수 있습니다.

## 경보 작업 비활성화
<a name="cloudwatch-examples-using-alarm-actions-disabling"></a>

파일 이름이 `cw_disablealarmactions.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch에 액세스하려면 `AWS.CloudWatch` 서비스 객체를 생성합니다. CloudWatch 경보의 이름을 포함하는 JSON 객체를 생성합니다. `disableAlarmActions` 메서드를 호출하여 이 경보에 대한 작업을 비활성화합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

cw.disableAlarmActions(
  { AlarmNames: ["Web_Server_CPU_Utilization"] },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cw_disablealarmactions.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/cloudwatch/cw_disablealarmactions.js)에서 찾을 수 있습니다.

# Amazon CloudWatch에서 지표 가져오기
<a name="cloudwatch-examples-getting-metrics"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 게시된 CloudWatch 지표의 목록을 검색하는 방법
+ CloudWatch 지표에 데이터 포인트를 게시하는 방법

## 시나리오
<a name="cloudwatch-examples-getting-metrics-scenario"></a>

지표는 시스템 성능에 대한 데이터입니다. Amazon EC2 인스턴스 같은 일부 리소스나 자체 애플리케이션 지표에 대한 세부 모니터링을 활성화할 수 있습니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 CloudWatch에서 지표를 가져오고 이벤트를 Amazon CloudWatch Events로 보냅니다. Node.js 모듈은 SDK for JavaScript로 `CloudWatch` 클라이언트 클래스의 다음 메서드를 사용하여 CloudWatch에서 지표를 가져옵니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#listMetrics-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#listMetrics-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#putMetricData-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatch.html#putMetricData-property)

CloudWatch 지표에 대한 자세한 내용은 *Amazon CloudWatch 사용 설명서*의 [Amazon CloudWatch 지표 사용](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)을 참조하세요.

## 사전 필수 작업
<a name="cloudwatch-examples-getting-metrics-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 지표 나열
<a name="cloudwatch-examples-getting-metrics-listing"></a>

파일 이름이 `cw_listmetrics.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch에 액세스하려면 `AWS.CloudWatch` 서비스 객체를 생성합니다. `AWS/Logs` 네임스페이스 내에 지표를 나열하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `listMetrics` 메서드를 호출하여 `IncomingLogEvents` 지표를 나열합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  Dimensions: [
    {
      Name: "LogGroupName" /* required */,
    },
  ],
  MetricName: "IncomingLogEvents",
  Namespace: "AWS/Logs",
};

cw.listMetrics(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Metrics", JSON.stringify(data.Metrics));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cw_listmetrics.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/cloudwatch/cw_listmetrics.js)에서 찾을 수 있습니다.

## 사용자 지정 지표 제출
<a name="cloudwatch-examples-getting-metrics-publishing-custom"></a>

파일 이름이 `cw_putmetricdata.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch에 액세스하려면 `AWS.CloudWatch` 서비스 객체를 생성합니다. `PAGES_VISITED` 사용자 지정 지표에 대한 데이터 포인트를 제출하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `putMetricData` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

// Create parameters JSON for putMetricData
var params = {
  MetricData: [
    {
      MetricName: "PAGES_VISITED",
      Dimensions: [
        {
          Name: "UNIQUE_PAGES",
          Value: "URLS",
        },
      ],
      Unit: "None",
      Value: 1.0,
    },
  ],
  Namespace: "SITE/TRAFFIC",
};

cw.putMetricData(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", JSON.stringify(data));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cw_putmetricdata.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/cloudwatch/cw_putmetricdata.js)에서 찾을 수 있습니다.

# Amazon CloudWatch Events에 이벤트 전송
<a name="cloudwatch-examples-sending-events"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 이벤트를 트리거하는 데 사용되는 규칙을 생성하고 업데이트하는 방법.
+ 이벤트에 응답할 하나 이상의 대상을 정의하는 방법.
+ 처리를 위해 대상과 일치하는 이벤트를 전송하는 방법.

## 시나리오
<a name="cloudwatch-examples-sending-events-scenario"></a>

CloudWatch Events는 다양한 대상으로의 Amazon Web Services 리소스 변경 사항을 설명하는 시스템 이벤트의 스트림을 거의 실시간으로 전달합니다. 단순한 규칙을 사용하여 이벤트를 하나 이상의 대상 함수 또는 스트림에 일치시키고 라우팅할 수 있습니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 이벤트를 CloudWatch Events에 전송합니다. Node.js 모듈은 SDK for JavaScript로 `CloudWatchEvents` 클라이언트 클래스의 다음 메서드를 사용하여 인스턴스를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putRule-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putRule-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putTargets-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putTargets-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putEvents-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchEvents.html#putEvents-property)

CloudWatch Events에 대한 자세한 내용은 *Amazon CloudWatch Events 사용 설명서*의 [PutEvents로 이벤트 추가](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/AddEventsPutEvents.html)를 참조하세요.

## 사전 필수 작업
<a name="cloudwatch-examples-sending-events-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ **hello-world** 블루프린트를 사용하는 Lambda 함수를 생성하여 이벤트의 대상 역할을 하도록 합니다. 방법을 알아보려면 *Amazon CloudWatch Events 사용 설명서*의 [1단계: AWS Lambda 함수 생성](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/LogEC2InstanceState.html)을 참조하세요.
+ CloudWatch Events에 권한을 부여하는 정책이 있고 신뢰할 수 있는 엔터티인 `events.amazonaws.com`을 포함하는 IAM 역할을 생성합니다. IAM 역할 생성에 관한 자세한 내용은 *IAM 사용 설명서*의 [AWS 서비스에 대한 권한을 위임할 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) 섹션을 참조하세요.

IAM 역할을 생성할 때 다음 역할 정책을 사용합니다.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Sid": "CloudWatchEventsFullAccess",
         "Effect": "Allow",
         "Action": "events:*",
         "Resource": "*"
      },
      {
         "Sid": "IAMPassRoleForCloudWatchEvents",
         "Effect": "Allow",
         "Action": "iam:PassRole",
         "Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets"
      }      
   ]
}
```

------

IAM 역할을 생성할 때 다음과 같은 신뢰 관계를 사용합니다.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Principal": {
            "Service": "events.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
      }      
   ]
}
```

------

## 예약된 규칙 생성
<a name="cloudwatch-examples-sending-events-rules"></a>

파일 이름이 `cwe_putrule.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch Events에 액세스하려면 `AWS.CloudWatchEvents` 서비스 객체를 생성합니다. 새로운 예약 규칙을 지정하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 다음이 포함됩니다.
+ 규칙의 이름입니다
+ 이전에 생성한 IAM 역할의 ARN
+ 5분마다 규칙 트리거링을 예약할 표현식

`putRule` 메서드를 호출하여 규칙을 생성합니다. 콜백은 새로운 규칙 또는 업데이트된 규칙의 ARN을 반환합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Name: "DEMO_EVENT",
  RoleArn: "IAM_ROLE_ARN",
  ScheduleExpression: "rate(5 minutes)",
  State: "ENABLED",
};

cwevents.putRule(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.RuleArn);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cwe_putrule.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-events/cwe_putrule.js)에서 찾을 수 있습니다.

## AWS Lambda 함수 대상 추가
<a name="cloudwatch-examples-sending-events-targets"></a>

파일 이름이 `cwe_puttargets.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch Events에 액세스하려면 `AWS.CloudWatchEvents` 서비스 객체를 생성합니다. 생성한 Lambda 함수의 ARN을 포함하여 대상에 연결할 규칙을 지정하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `putTargets` 서비스 객체의 `AWS.CloudWatchEvents` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Rule: "DEMO_EVENT",
  Targets: [
    {
      Arn: "LAMBDA_FUNCTION_ARN",
      Id: "myCloudWatchEventsTarget",
    },
  ],
};

cwevents.putTargets(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cwe_puttargets.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-events/cwe_puttargets.js)에서 찾을 수 있습니다.

## 이벤트 전송
<a name="cloudwatch-examples-sending-events-putevents"></a>

파일 이름이 `cwe_putevents.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch Events에 액세스하려면 `AWS.CloudWatchEvents` 서비스 객체를 생성합니다. 이벤트를 전송하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이벤트마다 해당 이벤트의 소스, 해당 이벤트의 영향을 받은 모든 리소스의 ARN, 해당 이벤트의 세부 정보를 포함시킵니다. `putEvents` 서비스 객체의 `AWS.CloudWatchEvents` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Entries: [
    {
      Detail: '{ "key1": "value1", "key2": "value2" }',
      DetailType: "appRequestSubmitted",
      Resources: ["RESOURCE_ARN"],
      Source: "com.company.app",
    },
  ],
};

cwevents.putEvents(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Entries);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cwe_putevents.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-events/cwe_putevents.js)에서 찾을 수 있습니다.

# Amazon CloudWatch Logs 구독 필터 사용
<a name="cloudwatch-examples-subscriptions"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ CloudWatch Logs에서 로그 이벤트에 대한 필터를 생성하고 삭제하는 방법

## 시나리오
<a name="cloudwatch-examples-subscriptions-scenario"></a>

구독을 사용하면 CloudWatch Logs의 로그 이벤트 실시간 피드에 액세스할 수 있으며 사용자 지정 처리, 분석 또는 다른 시스템에 로드하기 위해 해당 피드를 Amazon Kinesis 스트림 또는 AWS Lambda와 같은 다른 서비스에 전달할 수 있습니다. 구독 필터는 AWS 리소스에 전달되는 로그 이벤트를 필터링하는 데 사용할 패턴을 정의합니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 CloudWatch Logs에서 구독 필터를 나열, 생성 및 삭제합니다. 로그 이벤트의 대상은 Lambda 함수입니다. Node.js 모듈은 SDK for JavaScript로 `CloudWatchLogs` 클라이언트 클래스의 다음 메서드를 사용하여 구독 필터를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html#putSubscriptionFilters-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html#putSubscriptionFilters-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html#describeSubscriptionFilters-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html#describeSubscriptionFilters-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html#deleteSubscriptionFilter-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudWatchLogs.html#deleteSubscriptionFilter-property)

자세한 내용은 *Amazon CloudWatch Logs 사용 설명서*의 [구독을 통한 로그 데이터 실시간 처리](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions.html)를 참조하세요.

## 사전 필수 작업
<a name="cloudwatch-examples-subscriptions-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ Lambda 함수를 로그 이벤트의 대상으로 생성합니다. 이 함수의 ARN을 사용해야 합니다. Lambda 함수 설정에 대한 자세한 내용은 *Amazon CloudWatch Logs 사용 설명서*의 [AWS Lambda 구독 필터](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html#LambdaFunctionExample)를 참조하세요.
+ 생성한 Lambda 함수를 간접 호출할 권한을 부여하고 CloudWatch Logs에 대한 모든 액세스 권한을 부여하는 정책이 있는 IAM 역할을 생성하거나, Lambda 함수에 대해 생성한 실행 역할에 다음 정책을 적용합니다. IAM 역할 생성에 관한 자세한 내용은 *IAM 사용 설명서*의 [AWS 서비스에 대한 권한을 위임할 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) 섹션을 참조하세요.

IAM 역할을 생성할 때 다음 역할 정책을 사용합니다.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Action": [
            "logs:CreateLogGroup",
            "logs:CreateLogStream",
            "logs:PutLogEvents"
         ],
         "Resource": "arn:aws:logs:*:*:*"
      },
      {
         "Effect": "Allow",
         "Action": [
            "lambda:InvokeFunction"
         ],
         "Resource": [
            "*"
         ]
      }
   ]
}
```

------

## 기존 구독 필터 설명
<a name="cloudwatch-examples-subscriptions-describing"></a>

파일 이름이 `cwl_describesubscriptionfilters.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch Logs에 액세스하려면 `AWS.CloudWatchLogs` 서비스 객체를 생성합니다. 로그 그룹의 이름 및 설명할 최대 필터 수를 포함하여 기존 필터를 설명하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `describeSubscriptionFilters` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the CloudWatchLogs service object
var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" });

var params = {
  logGroupName: "GROUP_NAME",
  limit: 5,
};

cwl.describeSubscriptionFilters(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.subscriptionFilters);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cwl_describesubscriptionfilters.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-logs/cwl_describesubscriptionfilters.js)에서 찾을 수 있습니다.

## 구독 필터 생성
<a name="cloudwatch-examples-subscriptions-creating"></a>

파일 이름이 `cwl_putsubscriptionfilter.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch Logs에 액세스하려면 `AWS.CloudWatchLogs` 서비스 객체를 생성합니다. 대상 Lambda 함수의 ARN, 필터의 이름, 필터링을 위한 문자열 패턴, 로그 그룹의 이름 등을 포함하여 필터를 생성하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `putSubscriptionFilters` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the CloudWatchLogs service object
var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" });

var params = {
  destinationArn: "LAMBDA_FUNCTION_ARN",
  filterName: "FILTER_NAME",
  filterPattern: "ERROR",
  logGroupName: "LOG_GROUP",
};

cwl.putSubscriptionFilter(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cwl_putsubscriptionfilter.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-logs/cwl_putsubscriptionfilter.js)에서 찾을 수 있습니다.

## 구독 필터 삭제
<a name="cloudwatch-examples-subscriptions-deleting"></a>

파일 이름이 `cwl_deletesubscriptionfilters.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. CloudWatch Logs에 액세스하려면 `AWS.CloudWatchLogs` 서비스 객체를 생성합니다. 필터 및 로그 그룹의 이름을 포함하여 필터를 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `deleteSubscriptionFilters` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the CloudWatchLogs service object
var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" });

var params = {
  filterName: "FILTER",
  logGroupName: "LOG_GROUP",
};

cwl.deleteSubscriptionFilter(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node cwl_deletesubscriptionfilter.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/cloudwatch-logs/cwl_deletesubscriptionfilter.js)에서 찾을 수 있습니다.

# Amazon DynamoDB 예제
<a name="dynamodb-examples"></a>

Amazon DynamoDB는 문서 모델과 키-값 스토어 모델을 모두 지원하는 완전 관리형 NoSQL 클라우드 데이터베이스입니다. 전용 데이터베이스 서버를 프로비저닝하거나 유지 관리할 필요 없이 데이터에 대해 스키마 없는 테이블을 생성합니다.

![\[JavaScript 환경, SDK, DynamoDB 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-dynamodb.png)


DynamoDB용 JavaScript API는 `AWS.DynamoDB`, `AWS.DynamoDBStreams` 및 `AWS.DynamoDB.DocumentClient` 클라이언트 클래스를 통해 노출됩니다. DynamoDB 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html), [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDBStreams.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDBStreams.html), [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html) 섹션을 참조하세요.

**Topics**
+ [DynamoDB에서 테이블 생성 및 사용](dynamodb-examples-using-tables.md)
+ [DynamoDB에서 단일 항목 읽기 및 쓰기](dynamodb-example-table-read-write.md)
+ [DynamoDB에서 배치로 항목 읽기 및 쓰기](dynamodb-example-table-read-write-batch.md)
+ [DynamoDB 테이블 쿼리 및 스캔](dynamodb-example-query-scan.md)
+ [DynamoDB 문서 클라이언트 사용](dynamodb-example-document-client.md)

# DynamoDB에서 테이블 생성 및 사용
<a name="dynamodb-examples-using-tables"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ DynamoDB에서 데이터를 저장하고 검색하는 데 사용되는 테이블을 생성하고 관리하는 방법

## 시나리오
<a name="dynamodb-examples-using-tables-scenario"></a>

다른 데이터베이스 시스템과 마찬가지로 DynamoDB는 데이터를 테이블에 저장합니다. DynamoDB 테이블은 행과 유사한 항목으로 구성되는 데이터의 모음입니다. DynamoDB에서 데이터를 저장하거나 데이터에 액세스하려면 테이블을 생성하고 테이블로 작업합니다.

이 예에서는 일련의 Node.js 모듈을 사용하여 DynamoDB 테이블의 기본 작업을 수행합니다. 이 코드는 SDK for JavaScript에서 `AWS.DynamoDB` 클라이언트 클래스의 다음 메서드를 사용하여 테이블을 생성하고 테이블로 작업합니다.
+ [createTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property)
+ [listTables](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#listTables-property)
+ [describeTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#describeTable-property)
+ [deleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#deleteTable-property)

## 사전 필수 작업
<a name="dynamodb-examples-using-tables-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 표 생성
<a name="dynamodb-examples-using-tables-creating-a-table"></a>

파일 이름이 `ddb_createtable.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 테이블을 생성하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 각 속성의 이름과 데이터 형식, 키 스키마, 테이블의 이름, 프로비저닝할 처리량의 단위가 포함됩니다. DynamoDB 객체의 `createTable` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  AttributeDefinitions: [
    {
      AttributeName: "CUSTOMER_ID",
      AttributeType: "N",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      AttributeType: "S",
    },
  ],
  KeySchema: [
    {
      AttributeName: "CUSTOMER_ID",
      KeyType: "HASH",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      KeyType: "RANGE",
    },
  ],
  ProvisionedThroughput: {
    ReadCapacityUnits: 1,
    WriteCapacityUnits: 1,
  },
  TableName: "CUSTOMER_LIST",
  StreamSpecification: {
    StreamEnabled: false,
  },
};

// Call DynamoDB to create the table
ddb.createTable(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Table Created", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_createtable.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_createtable.js)에서 찾을 수 있습니다.

## 테이블 목록 조회
<a name="dynamodb-examples-using-tables-listing-tables"></a>

파일 이름이 `ddb_listtables.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 테이블을 나열하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다, 이 예제에서는 나열되는 테이블 수를 10으로 제한합니다. DynamoDB 객체의 `listTables` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

// Call DynamoDB to retrieve the list of tables
ddb.listTables({ Limit: 10 }, function (err, data) {
  if (err) {
    console.log("Error", err.code);
  } else {
    console.log("Table names are ", data.TableNames);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_listtables.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_listtables.js)에서 찾을 수 있습니다.

## 테이블 설명
<a name="dynamodb-examples-using-tables-describing-a-table"></a>

파일 이름이 `ddb_describetable.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 테이블을 설명하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 명령줄 파라미터로 제공되는 테이블의 이름이 포함됩니다. DynamoDB 객체의 `describeTable` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: process.argv[2],
};

// Call DynamoDB to retrieve the selected table descriptions
ddb.describeTable(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Table.KeySchema);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_describetable.js TABLE_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_describetable.js)에서 찾을 수 있습니다.

## 테이블 삭제
<a name="dynamodb-examples-using-tables-deleting-a-table"></a>

파일 이름이 `ddb_deletetable.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 테이블을 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예에서는 명령줄 파라미터로 제공되는 테이블의 이름을 포함합니다. DynamoDB 객체의 `deleteTable` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: process.argv[2],
};

// Call DynamoDB to delete the specified table
ddb.deleteTable(params, function (err, data) {
  if (err && err.code === "ResourceNotFoundException") {
    console.log("Error: Table not found");
  } else if (err && err.code === "ResourceInUseException") {
    console.log("Error: Table in use");
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_deletetable.js TABLE_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_deletetable.js)에서 찾을 수 있습니다.

# DynamoDB에서 단일 항목 읽기 및 쓰기
<a name="dynamodb-example-table-read-write"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ DynamoDB 테이블에서 항목을 추가하는 방법
+ DynamoDB 테이블에서 항목을 검색하는 방법
+ DynamoDB 테이블에서 항목을 삭제하는 방법

## 시나리오
<a name="dynamodb-example-table-read-write-scenario"></a>

이 예에서는 일련의 Node.js 모듈에서 `AWS.DynamoDB` 클라이언트 클래스의 다음 메서드를 사용하여 DynamoDB 테이블에서 항목 하나를 읽고 씁니다.
+ [putItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#putItem-property)
+ [getItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property)
+ [deleteItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#deleteItem-property)

## 사전 필수 작업
<a name="dynamodb-example-table-read-write-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 액세스할 수 있는 항목이 포함된 DynamoDB 테이블을 생성합니다. DynamoDB 테이블 생성에 관한 자세한 내용은 [DynamoDB에서 테이블 생성 및 사용](dynamodb-examples-using-tables.md) 섹션을 참조하세요.

## 항목 쓰기
<a name="dynamodb-example-table-read-write-writing-an-item"></a>

파일 이름이 `ddb_putitem.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 항목을 추가하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블의 이름 및 설정할 속성과 각 속성의 값을 정의하는 맵이 포함됩니다. DynamoDB 객체의 `putItem` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "CUSTOMER_LIST",
  Item: {
    CUSTOMER_ID: { N: "001" },
    CUSTOMER_NAME: { S: "Richard Roe" },
  },
};

// Call DynamoDB to add the item to the table
ddb.putItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_putitem.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_putitem.js)에서 찾을 수 있습니다.

## 항목 가져오기
<a name="dynamodb-example-table-read-write-getting-an-item"></a>

파일 이름이 `ddb_getitem.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 가져올 항목을 식별하려면 테이블의 해당 항목에 대한 기본 키의 값을 제공해야 합니다. 기본적으로 `getItem` 메서드는 항목에 정의된 모든 속성 값을 반환합니다. 가능한 모든 속성 값의 일부만 가져오려면 프로젝션 표현식을 지정합니다.

항목을 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블의 이름, 가져오는 항목에 대한 키의 이름과 값, 검색할 항목 속성을 식별하는 프로젝션 표현식이 포함됩니다. DynamoDB 객체의 `getItem` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "TABLE",
  Key: {
    KEY_NAME: { N: "001" },
  },
  ProjectionExpression: "ATTRIBUTE_NAME",
};

// Call DynamoDB to read the item from the table
ddb.getItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Item);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_getitem.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_getitem.js)에서 찾을 수 있습니다.

## 항목 삭제
<a name="dynamodb-example-table-read-write-deleting-an-item"></a>

파일 이름이 `ddb_deleteitem.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 항목을 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예에서는 테이블의 이름과 삭제하려는 항목의 키 이름 및 값을 포함합니다. DynamoDB 객체의 `deleteItem` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "TABLE",
  Key: {
    KEY_NAME: { N: "VALUE" },
  },
};

// Call DynamoDB to delete the item from the table
ddb.deleteItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_deleteitem.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_deleteitem.js)에서 찾을 수 있습니다.

# DynamoDB에서 배치로 항목 읽기 및 쓰기
<a name="dynamodb-example-table-read-write-batch"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ DynamoDB 테이블에서 항목의 배치를 읽고 쓰는 방법

## 시나리오
<a name="dynamodb-example-table-read-write-batch-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 항목의 배치를 DynamoDB table 테이블에 넣고 항목의 배치를 읽습니다. 이 코드는 SDK for JavaScript에서 DynamoDB 클라이언트 클래스의 다음 메서드를 사용하여 배치 읽기 및 쓰기 작업을 수행합니다.
+ [batchGetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#batchGetItem-property)
+ [batchWriteItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#batchWriteItem-property)

## 사전 필수 작업
<a name="dynamodb-example-table-read-write-batch-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 액세스할 수 있는 항목이 포함된 DynamoDB 테이블을 생성합니다. DynamoDB 테이블 생성에 관한 자세한 내용은 [DynamoDB에서 테이블 생성 및 사용](dynamodb-examples-using-tables.md) 섹션을 참조하세요.

## 배치로 항목 읽기
<a name="dynamodb-example-table-read-write-batch-reading"></a>

파일 이름이 `ddb_batchgetitem.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 항목의 배치를 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 읽을 하나 이상 테이블의 이름, 각 테이블에서 읽을 키의 값, 반환할 속성을 지정하는 프로젝션 표현식이 포함됩니다. DynamoDB 객체의 `batchGetItem` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  RequestItems: {
    TABLE_NAME: {
      Keys: [
        { KEY_NAME: { N: "KEY_VALUE_1" } },
        { KEY_NAME: { N: "KEY_VALUE_2" } },
        { KEY_NAME: { N: "KEY_VALUE_3" } },
      ],
      ProjectionExpression: "KEY_NAME, ATTRIBUTE",
    },
  },
};

ddb.batchGetItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    data.Responses.TABLE_NAME.forEach(function (element, index, array) {
      console.log(element);
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_batchgetitem.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_batchgetitem.js)에서 찾을 수 있습니다.

## 배치로 항목 쓰기
<a name="dynamodb-example-table-read-write-batch-writing"></a>

파일 이름이 `ddb_batchwriteitem.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 항목의 배치를 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 항목을 쓰려는 테이블, 각 항목에 대해 쓰려는 키, 속성 및 해당 값이 이러한 객체입니다. DynamoDB 객체의 `batchWriteItem` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  RequestItems: {
    TABLE_NAME: [
      {
        PutRequest: {
          Item: {
            KEY: { N: "KEY_VALUE" },
            ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" },
            ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            KEY: { N: "KEY_VALUE" },
            ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" },
            ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" },
          },
        },
      },
    ],
  },
};

ddb.batchWriteItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_batchwriteitem.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_batchwriteitem.js)에서 찾을 수 있습니다.

# DynamoDB 테이블 쿼리 및 스캔
<a name="dynamodb-example-query-scan"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ DynamoDB 테이블에서 항목을 쿼리하고 스캔하는 방법

## 시나리오
<a name="dynamodb-example-table-query-scan-scenario"></a>

쿼리는 기본 키 속성 값만 사용하여 테이블 또는 보조 인덱스에서 항목을 찾습니다. 검색할 파티션 키 이름과 값을 제공해야 합니다. 정렬 키 이름과 값도 제공할 수 있으며, 비교 연산자를 사용하여 검색 결과를 좁힐 수 있습니다. 스캔은 지정된 테이블에서 모든 항목을 확인하여 항목을 찾습니다.

이 예에서는 일련의 Node.js 모듈을 사용하여 DynamoDB 테이블에서 검색하려는 항목을 하나 이상 식별합니다. 이 코드는 SDK for JavaScript에서 DynamoDB 클라이언트 클래스의 다음 메서드를 사용하여 테이블을 쿼리하고 스캔합니다.
+ [query](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property)
+ [스캔](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property)

## 사전 필수 작업
<a name="dynamodb-example-table-query-scan-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 액세스할 수 있는 항목이 포함된 DynamoDB 테이블을 생성합니다. DynamoDB 테이블 생성에 관한 자세한 내용은 [DynamoDB에서 테이블 생성 및 사용](dynamodb-examples-using-tables.md) 섹션을 참조하세요.

## 테이블 쿼리
<a name="dynamodb-example-table-query-scan-querying"></a>

이 예제에서는 비디오 시리즈에 대한 에피소드 정보가 포함된 테이블을 쿼리하여 지정된 어구가 자막에 포함되어 있는 에피소드 9 이후 두 번째 시즌 에피소드의 에피소드 제목과 자막을 반환합니다.

파일 이름이 `ddb_query.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 테이블을 쿼리하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블 이름, 쿼리에 필요한 `ExpressionAttributeValues`, 해당 값을 사용하여 쿼리에서 반환되는 항목을 정의하는 `KeyConditionExpression`, 각 항목에 대해 반환할 속성 값의 이름이 포함됩니다. DynamoDB 객체의 `query` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  ExpressionAttributeValues: {
    ":s": { N: "2" },
    ":e": { N: "09" },
    ":topic": { S: "PHRASE" },
  },
  KeyConditionExpression: "Season = :s and Episode > :e",
  ProjectionExpression: "Episode, Title, Subtitle",
  FilterExpression: "contains (Subtitle, :topic)",
  TableName: "EPISODES_TABLE",
};

ddb.query(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    //console.log("Success", data.Items);
    data.Items.forEach(function (element, index, array) {
      console.log(element.Title.S + " (" + element.Subtitle.S + ")");
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_query.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_query.js)에서 찾을 수 있습니다.

## 테이블 스캔
<a name="dynamodb-example-table-query-scan-scanning"></a>

파일 이름이 `ddb_scan.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB` 서비스 객체를 생성합니다. 테이블에서 항목을 스캔하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블의 이름, 일치하는 각 항목에 대해 반환할 속성 값의 목록, 결과 집합을 필터링하여 지정된 어구가 포함된 항목을 찾는 표현식이 포함됩니다. DynamoDB 객체의 `scan` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk");
// Set the AWS Region.
AWS.config.update({ region: "REGION" });

// Create DynamoDB service object.
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

const params = {
  // Specify which items in the results are returned.
  FilterExpression: "Subtitle = :topic AND Season = :s AND Episode = :e",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: "SubTitle2" },
    ":s": { N: 1 },
    ":e": { N: 2 },
  },
  // Set the projection expression, which are the attributes that you want.
  ProjectionExpression: "Season, Episode, Title, Subtitle",
  TableName: "EPISODES_TABLE",
};

ddb.scan(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
    data.Items.forEach(function (element, index, array) {
      console.log(
        "printing",
        element.Title.S + " (" + element.Subtitle.S + ")"
      );
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddb_scan.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddb_scan.js)에서 찾을 수 있습니다.

# DynamoDB 문서 클라이언트 사용
<a name="dynamodb-example-document-client"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 문서 클라이언트를 사용하여 DynamoDB 테이블에 액세스하는 방법

## 시나리오
<a name="dynamodb-example-document-client-scenario"></a>

DynamoDB 문서 클라이언트는 속성 값의 개념을 추상화하여 항목 작업을 간소화합니다. 이 추상화는 입력 파라미터로 제공되는 기본 JavaScript 유형에 주석을 달고, 주석이 달린 응답 데이터를 기본 JavaScript 유형으로 변환합니다.

DynamoDB 문서 클라이언트 클래스에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html) 섹션을 참조하세요. Amazon DynamoDB를 사용한 프로그래밍에 관한 자세한 내용은 *Amazon DynamoDB 개발자 안내서*의 [DynamoDB를 사용한 프로그래밍](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.html)을 참조하세요.

이 예제에서는 일련의 Node.js 모듈에서 문서 클라이언트를 사용하여 DynamoDB 테이블에 대한 기본 작업을 수행합니다. 이 코드는 SDK for JavaScript에서 DynamoDB 문서 클라이언트 클래스의 다음 메서드를 사용하여 테이블을 쿼리하고 스캔합니다.
+ [get](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property)
+ [put](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property)
+ [update](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property)
+ [query](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property)
+ [delete](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#delete-property)

## 사전 필수 작업
<a name="dynamodb-example-document-client-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 액세스할 수 있는 항목이 포함된 DynamoDB 테이블을 생성합니다. SDK for JavaScript를 사용하여 DynamoDB 테이블을 생성하는 방법에 관한 자세한 내용은 [DynamoDB에서 테이블 생성 및 사용](dynamodb-examples-using-tables.md) 단원을 참조하세요. [DynamoDB 콘솔](https://console.aws.amazon.com/dynamodb/)을 사용하여 테이블을 생성할 수도 있습니다.

## 테이블에서 항목 가져오기
<a name="dynamodb-example-document-client-get"></a>

파일 이름이 `ddbdoc_get.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB.DocumentClient` 객체를 생성합니다. 테이블에서 항목을 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블의 이름, 해당 테이블에 있는 해시 키의 이름, 가져올 항목에 대한 해시 키의 값이 포함됩니다. DynamoDB 문서 클라이언트의 `get` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  TableName: "EPISODES_TABLE",
  Key: { KEY_NAME: VALUE },
};

docClient.get(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Item);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddbdoc_get.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddbdoc_get.js)에서 찾을 수 있습니다.

## 테이블에 항목 넣기
<a name="dynamodb-example-document-client-put"></a>

파일 이름이 `ddbdoc_put.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB.DocumentClient` 객체를 생성합니다. 항목을 테이블에 쓰는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블의 이름, 해시 키 및 값을 포함하여 추가하거나 업데이트할 항목에 대한 설명, 항목에서 설정할 속성의 이름과 값이 포함됩니다. DynamoDB 문서 클라이언트의 `put` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  TableName: "TABLE",
  Item: {
    HASHKEY: VALUE,
    ATTRIBUTE_1: "STRING_VALUE",
    ATTRIBUTE_2: VALUE_2,
  },
};

docClient.put(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddbdoc_put.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddbdoc_put.js)에서 찾을 수 있습니다.

## 테이블에서 항목 업데이트
<a name="dynamodb-example-document-client-update"></a>

파일 이름이 `ddbdoc_update.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB.DocumentClient` 객체를 생성합니다. 항목을 테이블에 쓰는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블의 이름, 업데이트할 항목의 키, `ExpressionAttributeValues` 파라미터에서 값을 할당하는 토큰을 사용하여 업데이트할 항목의 속성을 정의하는 `UpdateExpressions` 집합이 포함됩니다. DynamoDB 문서 클라이언트의 `update` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

// Create variables to hold numeric key values
var season = SEASON_NUMBER;
var episode = EPISODES_NUMBER;

var params = {
  TableName: "EPISODES_TABLE",
  Key: {
    Season: season,
    Episode: episode,
  },
  UpdateExpression: "set Title = :t, Subtitle = :s",
  ExpressionAttributeValues: {
    ":t": "NEW_TITLE",
    ":s": "NEW_SUBTITLE",
  },
};

docClient.update(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddbdoc_update.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddbdoc_update.js)에서 찾을 수 있습니다.

## 테이블 쿼리
<a name="dynamodb-example-document-client-query"></a>

이 예제에서는 비디오 시리즈에 대한 에피소드 정보가 포함된 테이블을 쿼리하여 지정된 어구가 자막에 포함되어 있는 에피소드 9 이후 두 번째 시즌 에피소드의 에피소드 제목과 자막을 반환합니다.

파일 이름이 `ddbdoc_query.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB.DocumentClient` 객체를 생성합니다. 테이블을 쿼리하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블 이름, 쿼리에 필요한 `ExpressionAttributeValues`, 해당 값을 사용하여 쿼리에서 반환되는 항목을 정의하는 `KeyConditionExpression`이 포함됩니다. DynamoDB 문서 클라이언트의 `query` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  ExpressionAttributeValues: {
    ":s": 2,
    ":e": 9,
    ":topic": "PHRASE",
  },
  KeyConditionExpression: "Season = :s and Episode > :e",
  FilterExpression: "contains (Subtitle, :topic)",
  TableName: "EPISODES_TABLE",
};

docClient.query(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Items);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddbdoc_query.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddbdoc_query.js)에서 찾을 수 있습니다.

## 테이블에서 항목 삭제
<a name="dynamodb-example-document-client-delete"></a>

파일 이름이 `ddbdoc_delete.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 `AWS.DynamoDB.DocumentClient` 객체를 생성합니다. 테이블에서 항목을 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 테이블의 이름, 삭제할 항목에 대한 해시 키의 이름과 값이 포함됩니다. DynamoDB 문서 클라이언트의 `delete` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  Key: {
    HASH_KEY: VALUE,
  },
  TableName: "TABLE",
};

docClient.delete(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ddbdoc_delete.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascript/example_code/dynamodb/ddbdoc_delete.js)에서 찾을 수 있습니다.

# Amazon EC2 예제
<a name="ec2-examples"></a>

Amazon Elastic Compute Cloud(Amazon EC2)는 클라우드에서 가상 서버 호스팅을 제공하는 웹 서비스입니다. 이 서비스는 크기 조정 가능한 컴퓨팅 파워를 제공하여 개발자가 더 쉽게 웹 규모 클라우드 컴퓨팅을 수행할 수 있도록 설계되었습니다.

![\[JavaScript 환경, SDK, Amazon EC2 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-ec2.png)


Amazon EC2용 JavaScript API는 `AWS.EC2` 클라이언트 클래스를 통해 노출됩니다. Amazon EC2 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html) 섹션을 참조하세요.

**Topics**
+ [Amazon EC2 인스턴스 생성](ec2-example-creating-an-instance.md)
+ [Amazon EC2 인스턴스 관리](ec2-example-managing-instances.md)
+ [Amazon EC2 키 페어로 작업](ec2-example-key-pairs.md)
+ [Amazon EC2에서 리전 및 가용 영역 사용](ec2-example-regions-availability-zones.md)
+ [Amazon EC2의 보안 그룹 작업](ec2-example-security-groups.md)
+ [Amazon EC2에서 탄력적 IP 주소 사용](ec2-example-elastic-ip-addresses.md)

# Amazon EC2 인스턴스 생성
<a name="ec2-example-creating-an-instance"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 퍼블릭 Amazon Machine Image(AMI)에서 Amazon EC2 인스턴스를 생성하는 방법
+ 새 Amazon EC2 인스턴스를 생성하고 해당 인스턴스에 태그를 할당하는 방법

## 예제 소개
<a name="ec2-example-creating-an-instance-scenario"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon EC2 인스턴스를 생성하고 해당 인스턴스에 키 페어와 태그를 모두 할당합니다. 이 코드는 Amazon EC2 클라이언트 클래스의 다음 메서드를 사용하여 인스턴스를 생성하고 인스턴스에 태그를 지정할 수 있도록 SDK for JavaScript를 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#runInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#runInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createTags-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createTags-property)

## 사전 필수 작업
<a name="ec2-example-creating-an-instance-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 키 페어를 생성합니다. 세부 정보는 [Amazon EC2 키 페어로 작업](ec2-example-key-pairs.md)을 참조하세요. 이 예제에서는 키 페어의 이름을 사용합니다.

## 인스턴스 생성 및 태그 지정
<a name="ec2-example-creating-an-instance-and-tags"></a>

파일 이름이 `ec2_createinstances.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다.

할당할 키 페어의 이름과 실행할 AMI의 ID를 포함하여 AWS.EC2 클라이언트 클래스의 `runInstances` 메서드에 대한 파라미터를 전달할 객체를 생성합니다. `runInstances` 메서드를 호출하려면 파라미터를 전달하는 Amazon EC2 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 response를 처리합니다.

다음 코드로 `Name` 태그를 새 인스턴스에 추가하면 Amazon EC2 콘솔이 새 인스턴스를 인식하고 인스턴스 목록의 **이름** 필드에 표시합니다. 한 인스턴스에 최대 50개의 태그를 추가할 수 있으며, `createTags` 메서드에 대한 단일 호출에서 모두 추가할 수 있습니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Load credentials and set region from JSON file
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

// AMI is amzn-ami-2011.09.1.x86_64-ebs
var instanceParams = {
  ImageId: "AMI_ID",
  InstanceType: "t2.micro",
  KeyName: "KEY_PAIR_NAME",
  MinCount: 1,
  MaxCount: 1,
};

// Create a promise on an EC2 service object
var instancePromise = new AWS.EC2({ apiVersion: "2016-11-15" })
  .runInstances(instanceParams)
  .promise();

// Handle promise's fulfilled/rejected states
instancePromise
  .then(function (data) {
    console.log(data);
    var instanceId = data.Instances[0].InstanceId;
    console.log("Created instance", instanceId);
    // Add tags to the instance
    tagParams = {
      Resources: [instanceId],
      Tags: [
        {
          Key: "Name",
          Value: "SDK Sample",
        },
      ],
    };
    // Create a promise on an EC2 service object
    var tagPromise = new AWS.EC2({ apiVersion: "2016-11-15" })
      .createTags(tagParams)
      .promise();
    // Handle promise's fulfilled/rejected states
    tagPromise
      .then(function (data) {
        console.log("Instance tagged");
      })
      .catch(function (err) {
        console.error(err, err.stack);
      });
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_createinstances.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_createinstances.js)에서 찾을 수 있습니다.

# Amazon EC2 인스턴스 관리
<a name="ec2-example-managing-instances"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon EC2 인스턴스에 대한 기본 정보를 검색하는 방법
+ Amazon EC2 인스턴스의 세부 모니터링을 시작하고 중지하는 방법
+ Amazon EC2 인스턴스를 시작하고 중지하는 방법
+ Amazon EC2 인스턴스 재부팅 방법

## 시나리오
<a name="ec2-example-managing-instances-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 여러 가지 기본 인스턴스 관리 작업을 수행합니다. Node.js 모듈은 SDK for JavaScript로 다음의 Amazon EC2 클라이언트 클래스 메서드를 사용하여 인스턴스를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#monitorInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#monitorInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#unmonitorInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#unmonitorInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#startInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#startInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#stopInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#stopInstances-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#rebootInstances-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#rebootInstances-property)

Amazon EC2 인스턴스 수명 주기에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [인스턴스 수명 주기](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html)를 참조하세요.

## 사전 필수 작업
<a name="ec2-example-managing-instances-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ Amazon EC2 인스턴스 생성 Amazon EC2 인스턴스 생성에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2 인스턴스](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html) 또는 **Amazon EC2 사용 설명서의 [Amazon EC2 인스턴스](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/Instances.html)를 참조하세요.

## 인스턴스 설명
<a name="ec2-example-managing-instances-describing"></a>

파일 이름이 `ec2_describeinstances.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. Amazon EC2 서비스 객체의 `describeInstances` 메서드를 직접 호출하여 인스턴스에 대한 세부 설명을 검색합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  DryRun: false,
};

// Call EC2 to retrieve policy for selected bucket
ec2.describeInstances(params, function (err, data) {
  if (err) {
    console.log("Error", err.stack);
  } else {
    console.log("Success", JSON.stringify(data));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_describeinstances.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_describeinstances.js)에서 찾을 수 있습니다.

## 인스턴스 모니터링 관리
<a name="ec2-example-managing-instances-monitoring"></a>

파일 이름이 `ec2_monitorinstances.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 모니터링을 제어하려는 인스턴스의 인스턴스 ID를 추가합니다.

명령줄 인수의 값(`ON` 또는 `OFF`)을 기반으로 Amazon EC2 서비스 객체의 `monitorInstances` 메서드를 호출하여 지정된 인스턴스에 대한 세부 모니터링을 시작하거나 `unmonitorInstances` 메서드를 직접 호출합니다. 이러한 인스턴스에 대한 모니터링을 변경하려고 시도하기 전에 `DryRun` 파라미터를 사용하여 인스턴스 모니터링을 변경할 권한이 있는지 여부를 테스트합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  InstanceIds: ["INSTANCE_ID"],
  DryRun: true,
};

if (process.argv[2].toUpperCase() === "ON") {
  // Call EC2 to start monitoring the selected instances
  ec2.monitorInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.monitorInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.InstanceMonitorings);
        }
      });
    } else {
      console.log("You don't have permission to change instance monitoring.");
    }
  });
} else if (process.argv[2].toUpperCase() === "OFF") {
  // Call EC2 to stop monitoring the selected instances
  ec2.unmonitorInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.unmonitorInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.InstanceMonitorings);
        }
      });
    } else {
      console.log("You don't have permission to change instance monitoring.");
    }
  });
}
```

예제를 실행하려면 명령줄에 다음을 입력하면서 `ON`을 지정하여 세부 모니터링을 시작하거나 `OFF`를 지정하여 모니터링을 중단합니다.

```
node ec2_monitorinstances.js ON
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_monitorinstances.js)에서 찾을 수 있습니다.

## 인스턴스 시작 및 중지
<a name="ec2-example-managing-instances-starting-stopping"></a>

파일 이름이 `ec2_startstopinstances.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 시작하거나 중지할 인스턴스의 인스턴스 ID를 추가합니다.

명령줄 인수의 값(`START` 또는 `STOP`)을 기반으로 Amazon EC2 서비스 객체의 `startInstances` 메서드를 호출하여 지정된 인스턴스를 시작하거나 `stopInstances` 메서드를 직접 호출하여 지정된 인스턴스를 중지합니다. 선택한 인스턴스를 실제로 시작하거나 중지하려고 시도하기 전에 `DryRun` 파라미터를 사용하여 권한이 있는지 여부를 테스트합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  InstanceIds: [process.argv[3]],
  DryRun: true,
};

if (process.argv[2].toUpperCase() === "START") {
  // Call EC2 to start the selected instances
  ec2.startInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.startInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.StartingInstances);
        }
      });
    } else {
      console.log("You don't have permission to start instances.");
    }
  });
} else if (process.argv[2].toUpperCase() === "STOP") {
  // Call EC2 to stop the selected instances
  ec2.stopInstances(params, function (err, data) {
    if (err && err.code === "DryRunOperation") {
      params.DryRun = false;
      ec2.stopInstances(params, function (err, data) {
        if (err) {
          console.log("Error", err);
        } else if (data) {
          console.log("Success", data.StoppingInstances);
        }
      });
    } else {
      console.log("You don't have permission to stop instances");
    }
  });
}
```

예제를 실행하려면 명령줄에 다음을 입력하면서 `START`를 지정하여 인스턴스를 시작하거나 `STOP`을 지정하여 인스턴스를 중지합니다.

```
node ec2_startstopinstances.js START INSTANCE_ID
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_startstopinstances.js)에서 찾을 수 있습니다.

## 인스턴스 재부팅
<a name="ec2-example-managing-instances-rebooting"></a>

파일 이름이 `ec2_rebootinstances.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 Amazon EC2 서비스 객체를 생성합니다. 재부팅할 인스턴스의 인스턴스 ID를 추가합니다. `AWS.EC2` 서비스 객체의 `rebootInstances` 메서드를 호출하여 지정된 인스턴스를 재부팅합니다. 실제로 인스턴스를 재부팅하려고 시도하기 전에 `DryRun` 파라미터를 사용하여 이러한 인스턴스를 재부팅할 권한이 있는지 여부를 테스트합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  InstanceIds: ["INSTANCE_ID"],
  DryRun: true,
};

// Call EC2 to reboot instances
ec2.rebootInstances(params, function (err, data) {
  if (err && err.code === "DryRunOperation") {
    params.DryRun = false;
    ec2.rebootInstances(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else if (data) {
        console.log("Success", data);
      }
    });
  } else {
    console.log("You don't have permission to reboot instances.");
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_rebootinstances.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_rebootinstances.js)에서 찾을 수 있습니다.

# Amazon EC2 키 페어로 작업
<a name="ec2-example-key-pairs"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 키 페어에 대한 정보를 검색하는 방법.
+ Amazon EC2 인스턴스에 액세스하기 위해 키 페어를 생성하는 방법
+ 기존 키 페어를 삭제하는 방법.

## 시나리오
<a name="ec2-example-key-pairs-scenario"></a>

Amazon EC2는 퍼블릭 키 암호화 기법을 사용하여 로그인 정보를 암호화 및 해독합니다. 퍼블릭 키 암호화 기법에서는 퍼블릭 키를 사용하여 데이터를 암호화한 후 수신자가 개인 키를 사용하여 해당 데이터를 해독합니다. 퍼블릭 키와 프라이빗 키를 *키 페어*라고 합니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 여러 가지 Amazon EC2 키 페어 관리 작업을 수행합니다. Node.js 모듈은 SDK for JavaScript로 Amazon EC2 클라이언트 클래스의 다음 메서드를 사용하여 인스턴스를 관리합니다
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createKeyPair-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createKeyPair-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#deleteKeyPair-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#deleteKeyPair-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeKeyPairs-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeKeyPairs-property)

Amazon EC2 키 페어에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2 키 페어](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) 또는 **Amazon EC2 사용 설명서의 [Amazon EC2 키 페어 및 Windows 인스턴스](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-key-pairs.html)를 참조하세요.

## 사전 필수 작업
<a name="ec2-example-key-pairs-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 키 페어 설명
<a name="ec2-example-key-pairs-describing"></a>

파일 이름이 `ec2_describekeypairs.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. `describeKeyPairs` 메서드가 모든 키 페어에 대한 설명을 반환하는 데 필요한 파라미터를 담을 비어 있는 JSON 객체를 생성합니다. JSON 파일에 포함된 파라미터의 `KeyName` 부분에 있는 키 페어의 이름 배열을 `describeKeyPairs` 메서드에 제공할 수도 있습니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

// Retrieve key pair descriptions; no params needed
ec2.describeKeyPairs(function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", JSON.stringify(data.KeyPairs));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_describekeypairs.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_describekeypairs.js)에서 찾을 수 있습니다.

## 키 페어 만들기
<a name="ec2-example-key-pairs-creating"></a>

각 키 페어에는 이름이 필요합니다. Amazon EC2는 사용자가 키 이름으로 지정한 이름에 퍼블릭 키를 연결합니다. 파일 이름이 `ec2_createkeypair.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 키 페어의 이름을 지정할 JSON 파라미터를 생성한 다음 해당 파라미터를 전달하여 `createKeyPair` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  KeyName: "KEY_PAIR_NAME",
};

// Create the key pair
ec2.createKeyPair(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log(JSON.stringify(data));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_createkeypair.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_createkeypair.js)에서 찾을 수 있습니다.

## 키 페어 삭제
<a name="ec2-example-key-pairs-deleting"></a>

파일 이름이 `ec2_deletekeypair.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 삭제하려는 키 페어의 이름을 지정할 JSON 파라미터를 생성합니다. 그런 다음 `deleteKeyPair` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  KeyName: "KEY_PAIR_NAME",
};

// Delete the key pair
ec2.deleteKeyPair(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Key Pair Deleted");
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_deletekeypair.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_deletekeypair.js)에서 찾을 수 있습니다.

# Amazon EC2에서 리전 및 가용 영역 사용
<a name="ec2-example-regions-availability-zones"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 리전과 가용 영역에 대한 설명을 검색하는 방법을 보여 줍니다.

## 시나리오
<a name="ec2-example-regions-availability-zones-scenario"></a>

Amazon EC2는 전 세계의 여러 곳에서 호스팅되고 있습니다. 이 위치들은 리전과 가용 영역으로 구성됩니다. 각 리전은 개별 지리 영역입니다. 각 리전은 *가용 영역*이라고 알려진 격리된 위치를 여러 개 가지고 있습니다. Amazon EC2는 인스턴스와 데이터를 여러 위치에 배치할 수 있는 기능을 제공합니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 리전과 가용 영역에 대한 세부 정보를 검색합니다. Node.js 모듈은 SDK for JavaScript로 아래의 Amazon EC2 클라이언트 클래스 메서드를 사용하여 인스턴스를 관리합니다
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeAvailabilityZones-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeAvailabilityZones-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeRegions-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeRegions-property)

리전 및 가용 영역에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [리전 및 가용 영역](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) 또는 **Amazon EC2 사용 설명서의 [리전 및 가용 영역](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/using-regions-availability-zones.html)을 참조하세요.

## 사전 필수 작업
<a name="ec2-example-regions-availability-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 리전 및 가용 영역 설명
<a name="ec2-example-regions-availability-describing"></a>

파일 이름이 `ec2_describeregionsandzones.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 파라미터로 전달할 비어 있는 JSON 객체를 생성합니다. 이 객체는 사용 가능한 모든 설명을 반환합니다. 그런 다음 `describeRegions` 및 `describeAvailabilityZones` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {};

// Retrieves all regions/endpoints that work with EC2
ec2.describeRegions(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Regions: ", data.Regions);
  }
});

// Retrieves availability zones only for region of the ec2 service object
ec2.describeAvailabilityZones(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Availability Zones: ", data.AvailabilityZones);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_describeregionsandzones.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_describeregionsandzones.js)에서 찾을 수 있습니다.

# Amazon EC2의 보안 그룹 작업
<a name="ec2-example-security-groups"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 보안 그룹에 대한 정보를 검색하는 방법.
+ Amazon EC2 인스턴스에 액세스하기 위한 보안 그룹을 생성하는 방법
+ 기존 보안 그룹을 삭제하는 방법.

## 시나리오
<a name="ec2-example-security-groups-scenario"></a>

Amazon EC2 보안 그룹은 하나 이상의 인스턴스에 대한 트래픽을 제어하는 가상 방화벽 역할을 합니다. 연결된 인스턴스에서 트래픽을 주고 받을 수 있도록 각 보안 그룹에 규칙을 추가합니다. 언제든지 보안 그룹에 대한 규칙을 수정할 수 있습니다. 새 규칙은 보안 그룹과 연결된 모든 인스턴스에 자동으로 적용됩니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 보안 그룹과 관련된 여러 가지 Amazon EC2 작업을 수행합니다. Node.js 모듈은 SDK for JavaScript로 아래의 Amazon EC2 클라이언트 클래스 메서드를 사용하여 인스턴스를 관리합니다
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeSecurityGroups-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeSecurityGroups-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#authorizeSecurityGroupIngress-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#authorizeSecurityGroupIngress-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createSecurityGroup-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#createSecurityGroup-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeVpcs-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeVpcs-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#deleteSecurityGroup-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#deleteSecurityGroup-property)

Amazon EC2 보안 그룹에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Linux 인스턴스용 Amazon EC2 Amazon 보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) 또는 **Amazon EC2 사용 설명서의 [Windows 인스턴스용 Amazon EC2 보안 그룹](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/using-network-security.html)을 참조하세요.

## 사전 필수 작업
<a name="ec2-example-security-groups-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 보안 그룹 설명
<a name="ec2-example-security-groups-describing"></a>

파일 이름이 `ec2_describesecuritygroups.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 설명하려는 보안 그룹의 그룹 ID를 포함하여 파라미터로 전달할 JSON 객체를 생성합니다. 그런 다음 Amazon EC2 서비스 객체의 `describeSecurityGroups` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  GroupIds: ["SECURITY_GROUP_ID"],
};

// Retrieve security group descriptions
ec2.describeSecurityGroups(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", JSON.stringify(data.SecurityGroups));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_describesecuritygroups.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_describesecuritygroups.js)에서 찾을 수 있습니다.

## 보안 그룹 및 규칙 생성
<a name="ec2-example-security-groups-creating"></a>

파일 이름이 `ec2_createsecuritygroup.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 보안 그룹의 이름, 설명, VPC의 ID를 지정하는 파라미터를 위한 JSON 객체를 생성합니다. 이 파라미터를 `createSecurityGroup` 메서드에 전달합니다.

보안 그룹을 성공적으로 생성한 후 인바운드 트래픽을 허용하기 위한 규칙을 정의할 수 있습니다. Amazon EC2 인스턴스가 트래픽을 수신할 IP 프로토콜과 인바운드 포트를 지정하는 파라미터를 위한 JSON 객체를 생성합니다. 이 파라미터를 `authorizeSecurityGroupIngress` 메서드에 전달합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Load credentials and set region from JSON file
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

// Variable to hold a ID of a VPC
var vpc = null;

// Retrieve the ID of a VPC
ec2.describeVpcs(function (err, data) {
  if (err) {
    console.log("Cannot retrieve a VPC", err);
  } else {
    vpc = data.Vpcs[0].VpcId;
    var paramsSecurityGroup = {
      Description: "DESCRIPTION",
      GroupName: "SECURITY_GROUP_NAME",
      VpcId: vpc,
    };
    // Create the instance
    ec2.createSecurityGroup(paramsSecurityGroup, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        var SecurityGroupId = data.GroupId;
        console.log("Success", SecurityGroupId);
        var paramsIngress = {
          GroupId: "SECURITY_GROUP_ID",
          IpPermissions: [
            {
              IpProtocol: "tcp",
              FromPort: 80,
              ToPort: 80,
              IpRanges: [{ CidrIp: "0.0.0.0/0" }],
            },
            {
              IpProtocol: "tcp",
              FromPort: 22,
              ToPort: 22,
              IpRanges: [{ CidrIp: "0.0.0.0/0" }],
            },
          ],
        };
        ec2.authorizeSecurityGroupIngress(paramsIngress, function (err, data) {
          if (err) {
            console.log("Error", err);
          } else {
            console.log("Ingress Successfully Set", data);
          }
        });
      }
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_createsecuritygroup.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_createsecuritygroup.js)에서 찾을 수 있습니다.

## 보안 그룹 삭제
<a name="ec2-example-security-groups-deleting"></a>

파일 이름이 `ec2_deletesecuritygroup.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 삭제할 보안 그룹의 이름을 지정할 JSON 파라미터를 생성합니다. 그런 다음 `deleteSecurityGroup` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  GroupId: "SECURITY_GROUP_ID",
};

// Delete the security group
ec2.deleteSecurityGroup(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Security Group Deleted");
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_deletesecuritygroup.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_deletesecuritygroup.js)에서 찾을 수 있습니다.

# Amazon EC2에서 탄력적 IP 주소 사용
<a name="ec2-example-elastic-ip-addresses"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 탄력적 IP 주소에 대한 설명을 검색하는 방법.
+ 탄력적 IP 주소를 할당하고 릴리스하는 방법.
+ Amazon EC2 인스턴스와 탄력적 IP 주소를 연결하는 방법

## 시나리오
<a name="ec2-example-elastic-ip-addresses-scenario"></a>

*탄력적 IP 주소*는 동적 클라우드 컴퓨팅을 위해 설계된 정적 IP 주소입니다. 탄력적 IP 주소는 AWS 계정과 연결됩니다. 퍼블릭 IP 주소로, 인터넷에서 연결할 수 있습니다. 인스턴스에 퍼블릭 IP 주소가 없는 경우 탄력적 IP 주소를 인스턴스에 연결하여 인터넷과의 통신을 활성화할 수 있습니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 탄력적 IP 주소와 관련된 여러 가지 Amazon EC2 작업을 수행합니다. Node.js 모듈은 SDK for JavaScript로 Amazon EC2 클라이언트 클래스의 다음 메서드를 사용하여 탄력적 IP 주소를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeAddresses-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeAddresses-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#allocateAddress-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#allocateAddress-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#associateAddress-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#associateAddress-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#releaseAddress-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#releaseAddress-property)

Amazon EC2의 탄력적 IP 주소에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [탄력적 IP 주소](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) 또는 **Amazon EC2 사용 설명서의 [탄력적 IP 주소](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-ip-addresses-eip.html)를 참조하세요.

## 사전 필수 작업
<a name="ec2-example-elastic-ip-addresses-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ Amazon EC2 인스턴스 생성 Amazon EC2 인스턴스 생성에 대한 자세한 내용은 **Amazon EC2 사용 설명서의 [Amazon EC2 인스턴스](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html) 또는 **Amazon EC2 사용 설명서의 [Amazon EC2 인스턴스](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/Instances.html)를 참조하세요.

## 탄력적 IP 주소 설명
<a name="ec2-example-elastic-ip-addresses-describing"></a>

파일 이름이 `ec2_describeaddresses.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. VPC에 있는 항목에서 반환되는 주소를 필터링하는 파라미터로 전달할 JSON 객체를 생성합니다. 모든 탄력적 IP 주소에 대한 설명을 검색하려면 파라미터 JSON에서 필터를 생략합니다. 그런 다음 Amazon EC2 서비스 객체의 `describeAddresses` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var params = {
  Filters: [{ Name: "domain", Values: ["vpc"] }],
};

// Retrieve Elastic IP address descriptions
ec2.describeAddresses(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", JSON.stringify(data.Addresses));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_describeaddresses.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_describeaddresses.js)에서 찾을 수 있습니다.

## 탄력적 IP 주소를 할당하고 Amazon EC2 인스턴스와 연결
<a name="ec2-example-elastic-ip-addresses-allocating-associating"></a>

파일 이름이 `ec2_allocateaddress.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 탄력적 IP 주소를 할당하는 데 사용되는 파라미터를 위한 JSON 객체를 생성합니다. 이 경우에는 `Domain`을 VPC로 지정합니다. Amazon EC2 서비스 객체의 `allocateAddress` 메서드를 직접 호출합니다.

호출이 성공하는 경우 콜백 함수에 대한 `data` 파라미터에는 할당된 탄력적 IP 주소를 식별하는 `AllocationId` 속성이 있습니다.

새로 할당된 주소의 `AllocationId`와 Amazon EC2 인스턴스의 `InstanceId`를 포함하여 탄력적 IP 주소를 Amazon EC2 인스턴스에 연결하는 데 사용되는 파라미터를 위한 JSON 객체를 생성합니다. 그런 다음 Amazon EC2 서비스 객체의 `associateAddresses` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var paramsAllocateAddress = {
  Domain: "vpc",
};

// Allocate the Elastic IP address
ec2.allocateAddress(paramsAllocateAddress, function (err, data) {
  if (err) {
    console.log("Address Not Allocated", err);
  } else {
    console.log("Address allocated:", data.AllocationId);
    var paramsAssociateAddress = {
      AllocationId: data.AllocationId,
      InstanceId: "INSTANCE_ID",
    };
    // Associate the new Elastic IP address with an EC2 instance
    ec2.associateAddress(paramsAssociateAddress, function (err, data) {
      if (err) {
        console.log("Address Not Associated", err);
      } else {
        console.log("Address associated:", data.AssociationId);
      }
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_allocateaddress.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_allocateaddress.js)에서 찾을 수 있습니다.

## 탄력적 IP 주소 해제
<a name="ec2-example-elastic-ip-addresses-releasing"></a>

파일 이름이 `ec2_releaseaddress.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon EC2에 액세스하려면 `AWS.EC2` 서비스 객체를 생성합니다. 탄력적 IP 주소를 릴리스하는 데 사용되는 파라미터를 위한 JSON 객체를 생성합니다. 이 경우에는 탄력적 IP 주소의 `AllocationId`가 지정됩니다. 탄력적 IP 주소를 릴리스하면 Amazon EC2 인스턴스에서 연결이 해제됩니다. Amazon EC2 서비스 객체의 `releaseAddress` 메서드를 직접 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create EC2 service object
var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" });

var paramsReleaseAddress = {
  AllocationId: "ALLOCATION_ID",
};

// Disassociate the Elastic IP address from EC2 instance
ec2.releaseAddress(paramsReleaseAddress, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Address released");
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_releaseaddress.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ec2/ec2_releaseaddress.js)에서 찾을 수 있습니다.

# AWS Elemental MediaConvert 예제
<a name="emc-examples"></a>

AWS Elemental MediaConvert는 브로드캐스트급 기능을 갖춘 파일 기반의 비디오 트랜스코딩 서비스입니다. 이 서비스를 사용하여 인터넷에서 브로드캐스트 및 비디오 온디맨드(VOD) 전달용 자산을 생성할 수 있습니다. 자세한 설명은 [https://docs.aws.amazon.com/mediaconvert/latest/ug/](https://docs.aws.amazon.com/mediaconvert/latest/ug/)를 참조하세요.

MediaConvert용 JavaScript API는 `AWS.MediaConvert` 클라이언트 클래스를 통해 노출됩니다. 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html)를 참조하세요.

**Topics**
+ [MediaConvert에서 트랜스코딩 작업 생성 및 관리](emc-examples-jobs.md)
+ [MediaConvert에서 작업 템플릿 사용](emc-examples-templates.md)

# MediaConvert에서 트랜스코딩 작업 생성 및 관리
<a name="emc-examples-jobs"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ MediaConvert에서 트랜스코딩 작업을 생성하는 방법
+ 트랜스코딩 작업을 취소하는 방법.
+ 완료된 트랜스코딩 작업에 대한 JSON을 검색하는 방법.
+ 최근에 생성된 최대 20개 작업에 대한 JSON 배열을 검색하는 방법.

## 시나리오
<a name="emc-examples-jobs-scenario"></a>

이 예에서는 Node.js 모듈을 사용하여 트랜스코딩 작업을 생성하고 관리할 MediaConvert를 직접적으로 호출합니다. 이 코드는 SDK for JavaScript에서 MediaConvert 클라이언트 클래스의 다음 메서드를 사용하여 이 작업을 수행합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#createJob-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#createJob-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#cancelJob-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#cancelJob-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#getJob-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#getJob-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#listJobs-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#listJobs-property)

## 사전 필수 작업
<a name="emc-examples-jobs-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 작업 입력 파일 및 출력 파일을 위한 스토리지를 제공하는 Amazon S3 버킷을 생성하고 구성합니다. 자세한 내용은 *AWS Elemental MediaConvert 사용 설명서*의 [파일 스토리지 생성](https://docs.aws.amazon.com/mediaconvert/latest/ug/set-up-file-locations.html) 섹션을 참조하세요.
+ 입력 스토리지를 위해 프로비저닝한 Amazon S3 버킷에 입력 비디오를 업로드합니다. 지원되는 입력 비디오 코덱 및 컨테이너 목록은 *AWS Elemental MediaConvert 사용 설명서*의 [지원되는 입력 코덱 및 컨테이너](https://docs.aws.amazon.com/mediaconvert/latest/ug/reference-codecs-containers-input.html)를 참조하세요.
+ 출력 파일이 저장된 Amazon S3 버킷 및 입력 파일에 대한 액세스 권한을 MediaConvert에 부여하는 IAM 역할을 생성합니다. 자세한 내용은 *AWS Elemental MediaConvert 사용 설명서*의 [IAM 권한 설정하기](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html)를 참조하세요.

## 단순 트랜스코딩 작업 정의
<a name="emc-examples-jobs-spec"></a>

파일 이름이 `emc_createjob.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. 트랜스코드 작업 파라미터를 정의하는 JSON을 생성합니다.

이러한 파라미터는 매우 세부적입니다. [AWS Elemental MediaConvert 콘솔](https://console.aws.amazon.com/mediaconvert/)을 사용하면 콘솔에서 작업 설정을 선택한 다음, **작업** 섹션 하단에서 **작업 JSON 표시**를 선택하여 JSON 작업 파라미터를 생성할 수 있습니다. 이 예제는 단순 작업용 JSON을 보여줍니다.

```
var params = {
  Queue: "JOB_QUEUE_ARN",
  UserMetadata: {
    Customer: "Amazon",
  },
  Role: "IAM_ROLE_ARN",
  Settings: {
    OutputGroups: [
      {
        Name: "File Group",
        OutputGroupSettings: {
          Type: "FILE_GROUP_SETTINGS",
          FileGroupSettings: {
            Destination: "s3://OUTPUT_BUCKET_NAME/",
          },
        },
        Outputs: [
          {
            VideoDescription: {
              ScalingBehavior: "DEFAULT",
              TimecodeInsertion: "DISABLED",
              AntiAlias: "ENABLED",
              Sharpness: 50,
              CodecSettings: {
                Codec: "H_264",
                H264Settings: {
                  InterlaceMode: "PROGRESSIVE",
                  NumberReferenceFrames: 3,
                  Syntax: "DEFAULT",
                  Softness: 0,
                  GopClosedCadence: 1,
                  GopSize: 90,
                  Slices: 1,
                  GopBReference: "DISABLED",
                  SlowPal: "DISABLED",
                  SpatialAdaptiveQuantization: "ENABLED",
                  TemporalAdaptiveQuantization: "ENABLED",
                  FlickerAdaptiveQuantization: "DISABLED",
                  EntropyEncoding: "CABAC",
                  Bitrate: 5000000,
                  FramerateControl: "SPECIFIED",
                  RateControlMode: "CBR",
                  CodecProfile: "MAIN",
                  Telecine: "NONE",
                  MinIInterval: 0,
                  AdaptiveQuantization: "HIGH",
                  CodecLevel: "AUTO",
                  FieldEncoding: "PAFF",
                  SceneChangeDetect: "ENABLED",
                  QualityTuningLevel: "SINGLE_PASS",
                  FramerateConversionAlgorithm: "DUPLICATE_DROP",
                  UnregisteredSeiTimecode: "DISABLED",
                  GopSizeUnits: "FRAMES",
                  ParControl: "SPECIFIED",
                  NumberBFramesBetweenReferenceFrames: 2,
                  RepeatPps: "DISABLED",
                  FramerateNumerator: 30,
                  FramerateDenominator: 1,
                  ParNumerator: 1,
                  ParDenominator: 1,
                },
              },
              AfdSignaling: "NONE",
              DropFrameTimecode: "ENABLED",
              RespondToAfd: "NONE",
              ColorMetadata: "INSERT",
            },
            AudioDescriptions: [
              {
                AudioTypeControl: "FOLLOW_INPUT",
                CodecSettings: {
                  Codec: "AAC",
                  AacSettings: {
                    AudioDescriptionBroadcasterMix: "NORMAL",
                    RateControlMode: "CBR",
                    CodecProfile: "LC",
                    CodingMode: "CODING_MODE_2_0",
                    RawFormat: "NONE",
                    SampleRate: 48000,
                    Specification: "MPEG4",
                    Bitrate: 64000,
                  },
                },
                LanguageCodeControl: "FOLLOW_INPUT",
                AudioSourceName: "Audio Selector 1",
              },
            ],
            ContainerSettings: {
              Container: "MP4",
              Mp4Settings: {
                CslgAtom: "INCLUDE",
                FreeSpaceBox: "EXCLUDE",
                MoovPlacement: "PROGRESSIVE_DOWNLOAD",
              },
            },
            NameModifier: "_1",
          },
        ],
      },
    ],
    AdAvailOffset: 0,
    Inputs: [
      {
        AudioSelectors: {
          "Audio Selector 1": {
            Offset: 0,
            DefaultSelection: "NOT_DEFAULT",
            ProgramSelection: 1,
            SelectorType: "TRACK",
            Tracks: [1],
          },
        },
        VideoSelector: {
          ColorSpace: "FOLLOW",
        },
        FilterEnable: "AUTO",
        PsiControl: "USE_PSI",
        FilterStrength: 0,
        DeblockFilter: "DISABLED",
        DenoiseFilter: "DISABLED",
        TimecodeSource: "EMBEDDED",
        FileInput: "s3://INPUT_BUCKET_AND_FILE_NAME",
      },
    ],
    TimecodeConfig: {
      Source: "EMBEDDED",
    },
  },
};
```

## 트랜스코딩 작업 생성
<a name="emc-examples-jobs-create"></a>

작업 파라미터 JSON을 생성한 후, 파라미터를 전달하는 `createJob` 서비스 객체를 호출하기 위한 promise를 생성하여 `AWS.MediaConvert` 메서드를 호출합니다. 그런 다음 promise 콜백에서 response를 처리합니다. 생성된 작업의 ID는 응답 `data`에서 반환됩니다.

```
// Create a promise on a MediaConvert object
var endpointPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" })
  .createJob(params)
  .promise();

// Handle promise's fulfilled/rejected status
endpointPromise.then(
  function (data) {
    console.log("Job created! ", data);
  },
  function (err) {
    console.log("Error", err);
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node emc_createjob.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/mediaconvert/emc_createjob.js)에서 찾을 수 있습니다.

## 트랜스코딩 작업 취소
<a name="emc-examples-jobs-cancel"></a>

파일 이름이 `emc_canceljob.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. 취소할 작업의 ID가 포함된 JSON을 생성합니다. 그런 다음 파라미터를 전달하는 `cancelJob` 서비스 객체를 호출하기 위한 promise를 생성하여 `AWS.MediaConvert` 메서드를 호출합니다. promise 콜백에서 응답을 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the Region
AWS.config.update({ region: "us-west-2" });
// Set MediaConvert to customer endpoint
AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" };

var params = {
  Id: "JOB_ID" /* required */,
};

// Create a promise on a MediaConvert object
var endpointPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" })
  .cancelJob(params)
  .promise();

// Handle promise's fulfilled/rejected status
endpointPromise.then(
  function (data) {
    console.log("Job  " + params.Id + " is canceled");
  },
  function (err) {
    console.log("Error", err);
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ec2_canceljob.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/mediaconvert/emc_canceljob.js)에서 찾을 수 있습니다.

## 최근 트랜스코딩 작업 나열
<a name="emc-examples-jobs-listing"></a>

파일 이름이 `emc_listjobs.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다.

목록을 `ASCENDING` 또는 `DESCENDING` 순서로 정렬할지 여부, 확인할 작업 대기열의 ARN, 포함할 작업의 상태 등을 지정하는 값을 포함하여 파라미터 JSON을 생성합니다. 그런 다음 파라미터를 전달하는 `listJobs` 서비스 객체를 호출하기 위한 promise를 생성하여 `AWS.MediaConvert` 메서드를 호출합니다. promise 콜백에서 응답을 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the Region
AWS.config.update({ region: "us-west-2" });
// Set the customer endpoint
AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" };

var params = {
  MaxResults: 10,
  Order: "ASCENDING",
  Queue: "QUEUE_ARN",
  Status: "SUBMITTED",
};

// Create a promise on a MediaConvert object
var endpointPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" })
  .listJobs(params)
  .promise();

// Handle promise's fulfilled/rejected status
endpointPromise.then(
  function (data) {
    console.log("Jobs: ", data);
  },
  function (err) {
    console.log("Error", err);
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node emc_listjobs.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/mediaconvert/emc_listjobs.js)에서 찾을 수 있습니다.

# MediaConvert에서 작업 템플릿 사용
<a name="emc-examples-templates"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ MediaConvert 작업 템플릿을 생성하는 방법
+ 작업 템플릿을 사용하여 트랜스코딩 작업을 생성하는 방법.
+ 모든 작업 템플릿의 목록을 표시하는 방법.
+ 작업 템플릿을 삭제하는 방법.

## 시나리오
<a name="emc-examples-templates-scenario"></a>

MediaConvert에서 트랜스코딩 작업을 생성하는 데 필요한 JSON은 많은 수의 설정을 포함하여 세부적입니다. 후속 작업을 생성하는 데 사용할 수 있는 작업 템플릿에 알려진 좋은 설정을 저장하여 작업 생성을 대폭 간소화할 수 있습니다. 이 예에서는 Node.js 모듈을 사용해 MediaConvert를 직접적으로 호출하여 작업 템플릿을 생성, 사용 및 관리합니다. 이 코드는 SDK for JavaScript에서 MediaConvert 클라이언트 클래스의 다음 메서드를 사용하여 이 작업을 수행합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#createJobTemplate-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#createJobTemplate-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#createJob-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#createJob-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#deleteJobTemplate-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#deleteJobTemplate-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#listJobTemplates-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/MediaConvert.html#listJobTemplates-property)

## 사전 필수 작업
<a name="emc-example-templates-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ Node.js를 설치합니다. 자세한 내용은 [Node.js](https://nodejs.org) 웹 사이트를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 출력 파일이 저장된 Amazon S3 버킷 및 입력 파일에 대한 액세스 권한을 MediaConvert에 부여하는 IAM 역할을 생성합니다. 자세한 내용은 *AWS Elemental MediaConvert 사용 설명서*의 [IAM 권한 설정하기](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html)를 참조하세요.

## 작업 템플릿 생성
<a name="emc-examples-templates-create"></a>

파일 이름이 `emc_create_jobtemplate.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다.

템플릿 생성을 위한 파라미터 JSON을 지정합니다. 이전에 성공한 작업에서 대부분의 JSON 파라미터를 사용하여 템플릿에서 `Settings` 값을 지정할 수 있습니다. 이 예제에서는 [MediaConvert에서 트랜스코딩 작업 생성 및 관리](emc-examples-jobs.md)의 작업 설정을 사용합니다.

파라미터를 전달하는 `createJobTemplate` 서비스 객체를 호출하기 위한 promise를 생성하여 `AWS.MediaConvert` 메서드를 호출합니다. 그런 다음 promise 콜백에서 response를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the Region
AWS.config.update({ region: "us-west-2" });
// Set the custom endpoint for your account
AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" };

var params = {
  Category: "YouTube Jobs",
  Description: "Final production transcode",
  Name: "DemoTemplate",
  Queue: "JOB_QUEUE_ARN",
  Settings: {
    OutputGroups: [
      {
        Name: "File Group",
        OutputGroupSettings: {
          Type: "FILE_GROUP_SETTINGS",
          FileGroupSettings: {
            Destination: "s3://BUCKET_NAME/",
          },
        },
        Outputs: [
          {
            VideoDescription: {
              ScalingBehavior: "DEFAULT",
              TimecodeInsertion: "DISABLED",
              AntiAlias: "ENABLED",
              Sharpness: 50,
              CodecSettings: {
                Codec: "H_264",
                H264Settings: {
                  InterlaceMode: "PROGRESSIVE",
                  NumberReferenceFrames: 3,
                  Syntax: "DEFAULT",
                  Softness: 0,
                  GopClosedCadence: 1,
                  GopSize: 90,
                  Slices: 1,
                  GopBReference: "DISABLED",
                  SlowPal: "DISABLED",
                  SpatialAdaptiveQuantization: "ENABLED",
                  TemporalAdaptiveQuantization: "ENABLED",
                  FlickerAdaptiveQuantization: "DISABLED",
                  EntropyEncoding: "CABAC",
                  Bitrate: 5000000,
                  FramerateControl: "SPECIFIED",
                  RateControlMode: "CBR",
                  CodecProfile: "MAIN",
                  Telecine: "NONE",
                  MinIInterval: 0,
                  AdaptiveQuantization: "HIGH",
                  CodecLevel: "AUTO",
                  FieldEncoding: "PAFF",
                  SceneChangeDetect: "ENABLED",
                  QualityTuningLevel: "SINGLE_PASS",
                  FramerateConversionAlgorithm: "DUPLICATE_DROP",
                  UnregisteredSeiTimecode: "DISABLED",
                  GopSizeUnits: "FRAMES",
                  ParControl: "SPECIFIED",
                  NumberBFramesBetweenReferenceFrames: 2,
                  RepeatPps: "DISABLED",
                  FramerateNumerator: 30,
                  FramerateDenominator: 1,
                  ParNumerator: 1,
                  ParDenominator: 1,
                },
              },
              AfdSignaling: "NONE",
              DropFrameTimecode: "ENABLED",
              RespondToAfd: "NONE",
              ColorMetadata: "INSERT",
            },
            AudioDescriptions: [
              {
                AudioTypeControl: "FOLLOW_INPUT",
                CodecSettings: {
                  Codec: "AAC",
                  AacSettings: {
                    AudioDescriptionBroadcasterMix: "NORMAL",
                    RateControlMode: "CBR",
                    CodecProfile: "LC",
                    CodingMode: "CODING_MODE_2_0",
                    RawFormat: "NONE",
                    SampleRate: 48000,
                    Specification: "MPEG4",
                    Bitrate: 64000,
                  },
                },
                LanguageCodeControl: "FOLLOW_INPUT",
                AudioSourceName: "Audio Selector 1",
              },
            ],
            ContainerSettings: {
              Container: "MP4",
              Mp4Settings: {
                CslgAtom: "INCLUDE",
                FreeSpaceBox: "EXCLUDE",
                MoovPlacement: "PROGRESSIVE_DOWNLOAD",
              },
            },
            NameModifier: "_1",
          },
        ],
      },
    ],
    AdAvailOffset: 0,
    Inputs: [
      {
        AudioSelectors: {
          "Audio Selector 1": {
            Offset: 0,
            DefaultSelection: "NOT_DEFAULT",
            ProgramSelection: 1,
            SelectorType: "TRACK",
            Tracks: [1],
          },
        },
        VideoSelector: {
          ColorSpace: "FOLLOW",
        },
        FilterEnable: "AUTO",
        PsiControl: "USE_PSI",
        FilterStrength: 0,
        DeblockFilter: "DISABLED",
        DenoiseFilter: "DISABLED",
        TimecodeSource: "EMBEDDED",
      },
    ],
    TimecodeConfig: {
      Source: "EMBEDDED",
    },
  },
};

// Create a promise on a MediaConvert object
var templatePromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" })
  .createJobTemplate(params)
  .promise();

// Handle promise's fulfilled/rejected status
templatePromise.then(
  function (data) {
    console.log("Success!", data);
  },
  function (err) {
    console.log("Error", err);
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node emc_create_jobtemplate.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/mediaconvert/emc_create_jobtemplate.js)에서 찾을 수 있습니다.

## 작업 템플릿에서 트랜스코딩 작업 생성
<a name="emc-examples-templates-createjob"></a>

파일 이름이 `emc_template_createjob.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다.

사용할 작업 템플릿의 이름, 생성하는 작업에 특정하게 사용할 `Settings`를 포함하여 작업 생성 파라미터 JSON을 생성합니다. 그런 다음 파라미터를 전달하는 `createJobs` 서비스 객체를 호출하기 위한 promise를 생성하여 `AWS.MediaConvert` 메서드를 호출합니다. promise 콜백에서 응답을 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the Region
AWS.config.update({ region: "us-west-2" });
// Set the custom endpoint for your account
AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" };

var params = {
  Queue: "QUEUE_ARN",
  JobTemplate: "TEMPLATE_NAME",
  Role: "ROLE_ARN",
  Settings: {
    Inputs: [
      {
        AudioSelectors: {
          "Audio Selector 1": {
            Offset: 0,
            DefaultSelection: "NOT_DEFAULT",
            ProgramSelection: 1,
            SelectorType: "TRACK",
            Tracks: [1],
          },
        },
        VideoSelector: {
          ColorSpace: "FOLLOW",
        },
        FilterEnable: "AUTO",
        PsiControl: "USE_PSI",
        FilterStrength: 0,
        DeblockFilter: "DISABLED",
        DenoiseFilter: "DISABLED",
        TimecodeSource: "EMBEDDED",
        FileInput: "s3://BUCKET_NAME/FILE_NAME",
      },
    ],
  },
};

// Create a promise on a MediaConvert object
var templateJobPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" })
  .createJob(params)
  .promise();

// Handle promise's fulfilled/rejected status
templateJobPromise.then(
  function (data) {
    console.log("Success! ", data);
  },
  function (err) {
    console.log("Error", err);
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node emc_template_createjob.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/mediaconvert/emc_template_createjob.js)에서 찾을 수 있습니다.

## 작업 템플릿 목록 표시
<a name="emc-examples-templates-listing"></a>

파일 이름이 `emc_listtemplates.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다.

`listTemplates` 클라이언트 클래스의 `AWS.MediaConvert` 메서드에 대한 요청 파라미터를 전달할 객체를 생성합니다. 나열할 템플릿(`NAME`, `CREATION DATE`, `SYSTEM`), 나열할 개수 및 정렬 순서를 결정하는 값을 포함시킵니다. `listTemplates` 메서드를 직접 호출하려면 MediaConvert 서비스 객체를 간접 호출하기 위한 promise를 생성하고 파라미터를 전달합니다. 그런 다음 promise 콜백에서 response를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the Region
AWS.config.update({ region: "us-west-2" });
// Set the customer endpoint
AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" };

var params = {
  ListBy: "NAME",
  MaxResults: 10,
  Order: "ASCENDING",
};

// Create a promise on a MediaConvert object
var listTemplatesPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" })
  .listJobTemplates(params)
  .promise();

// Handle promise's fulfilled/rejected status
listTemplatesPromise.then(
  function (data) {
    console.log("Success ", data);
  },
  function (err) {
    console.log("Error", err);
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node emc_listtemplates.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/mediaconvert/emc_template_createjob.js)에서 찾을 수 있습니다.

## 작업 템플릿 삭제
<a name="emc-examples-templates-delete"></a>

파일 이름이 `emc_deletetemplate.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다.

삭제하려는 작업 템플릿의 이름을 `deleteJobTemplate` 클라이언트 클래스의 `AWS.MediaConvert` 메서드에 대한 파라미터로 전달할 객체를 생성합니다. `deleteJobTemplate` 메서드를 직접 호출하려면 MediaConvert 서비스 객체를 간접 호출하기 위한 promise를 생성하고 파라미터를 전달합니다. promise 콜백에서 응답을 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the Region
AWS.config.update({ region: "us-west-2" });
// Set the customer endpoint
AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" };

var params = {
  Name: "TEMPLATE_NAME",
};

// Create a promise on a MediaConvert object
var deleteTemplatePromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" })
  .deleteJobTemplate(params)
  .promise();

// Handle promise's fulfilled/rejected status
deleteTemplatePromise.then(
  function (data) {
    console.log("Success ", data);
  },
  function (err) {
    console.log("Error", err);
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node emc_deletetemplate.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/mediaconvert/emc_deletetemplate.js)에서 찾을 수 있습니다.

# AWS IAM 예제
<a name="iam-examples"></a>

AWS Identity and Access Management(IAM)는 Amazon Web Services 고객이 AWS에서 사용자와 각 사용자 권한을 관리할 수 있도록 하는 웹 서비스입니다. 이 서비스는 클라우드 내에 AWS 제품을 사용하는 여러 사용자 또는 시스템이 있는 조직을 대상으로 합니다. IAM을 사용하면 사용자, 액세스 키와 같은 보안 자격 증명, 사용자가 액세스할 수 있는 AWS 리소스를 제어하는 권한을 중앙 관리할 수 있습니다.

![\[JavaScript 환경, SDK, IAM 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-iam.png)


IAM용 JavaScript API는 `AWS.IAM` 클라이언트 클래스를 통해 노출됩니다. IAM 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html) 섹션을 참조하세요.

**Topics**
+ [IAM 사용자 관리](iam-examples-managing-users.md)
+ [IAM 정책 작업](iam-examples-policies.md)
+ [IAM 액세스 키 관리](iam-examples-managing-access-keys.md)
+ [IAM 서버 인증서 작업](iam-examples-server-certificates.md)
+ [IAM 계정 별칭 관리](iam-examples-account-aliases.md)

# IAM 사용자 관리
<a name="iam-examples-managing-users"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ IAM 사용자 목록을 검색하는 방법
+ 사용자를 생성하고 삭제하는 방법.
+ 사용자 이름을 업데이트하는 방법.

## 시나리오
<a name="iam-examples-managing-users-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 IAM에서 사용자를 생성하고 관리합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.IAM` 클라이언트 클래스의 다음 메서드를 사용하여 사용자를 생성, 삭제 및 업데이트합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#createUser-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#createUser-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#listUsers-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#listUsers-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#updateUser-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#updateUser-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#getUser-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#getUser-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#deleteUser-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#deleteUser-property)

IAM 사용자에 대한 자세한 내용은 *IAM 사용 설명서*의 [IAM 사용자](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) 섹션을 참조하세요.

## 사전 필수 작업
<a name="iam-examples-managing-users-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 사용자 생성
<a name="iam-examples-managing-users-creating-users"></a>

파일 이름이 `iam_createuser.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 새 사용자에 사용하려는 사용자 이름이 명령줄 파라미터로 포함됩니다.

사용자 이름이 이미 있는 경우 `getUser` 서비스 객체의 `AWS.IAM`메서드를 호출합니다. 사용자 이름이 현재 없는 경우 `createUser` 메서드를 호출하여 사용자 이름을 생성합니다. 이름이 이미 있는 경우에는 그런 취지의 메시지를 콘솔에 표시합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
};

iam.getUser(params, function (err, data) {
  if (err && err.code === "NoSuchEntity") {
    iam.createUser(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data);
      }
    });
  } else {
    console.log(
      "User " + process.argv[2] + " already exists",
      data.User.UserId
    );
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_createuser.js USER_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_createuser.js)에서 찾을 수 있습니다.

## 계정의 사용자 목록 표시
<a name="iam-examples-managing-users-listing-users"></a>

파일 이름이 `iam_listusers.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 사용자 목록을 표시하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 `MaxItems` 파라미터를 10으로 설정하여 반환되는 수를 제한합니다. `listUsers` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다. 첫 번째 사용자의 이름과 생성 날짜를 콘솔에 씁니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  MaxItems: 10,
};

iam.listUsers(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var users = data.Users || [];
    users.forEach(function (user) {
      console.log("User " + user.UserName + " created", user.CreateDate);
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_listusers.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_listusers.js)에서 찾을 수 있습니다.

## 사용자 이름 업데이트
<a name="iam-examples-managing-users-updating-users"></a>

파일 이름이 `iam_updateuser.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 사용자 목룍을 표시하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성하고, 현재 및 새 사용자 이름을 모두 명령줄 파라미터로 지정합니다. `updateUser` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
  NewUserName: process.argv[3],
};

iam.updateUser(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 사용자의 현재 이름을 지정한 다음 새 사용자 이름을 지정하여 명령줄에 다음을 입력합니다.

```
node iam_updateuser.js ORIGINAL_USERNAME NEW_USERNAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_updateuser.js)에서 찾을 수 있습니다.

## 사용자 삭제
<a name="iam-examples-managing-users-deleting-users"></a>

파일 이름이 `iam_deleteuser.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 삭제하려는 사용자 이름이 명령줄 파라미터로 포함됩니다.

사용자 이름이 이미 있는 경우 `getUser` 서비스 객체의 `AWS.IAM`메서드를 호출합니다. 사용자 이름이 없는 경우 이를 알리는 메시지를 콘솔에 씁니다. 사용자가 있는 경우 `deleteUser` 메서드를 호출하여 사용자를 삭제합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
};

iam.getUser(params, function (err, data) {
  if (err && err.code === "NoSuchEntity") {
    console.log("User " + process.argv[2] + " does not exist.");
  } else {
    iam.deleteUser(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data);
      }
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_deleteuser.js USER_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_deleteuser.js)에서 찾을 수 있습니다.

# IAM 정책 작업
<a name="iam-examples-policies"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ IAM 정책을 생성하고 삭제하는 방법
+ IAM 정책을 역할에 연결하고 분리하는 방법

## 시나리오
<a name="iam-examples-policies-scenario"></a>

*정책*을 생성하여 사용자에게 권한을 부여합니다. 정책은 사용자가 수행할 수 있는 작업과 해당 작업이 영향을 미칠 수 있는 리소스 목록을 표시하는 문서입니다. 명시적으로 허용되지 않은 작업 또는 리소스는 기본적으로 모두 거부됩니다. 정책을 생성하여 사용자, 사용자 그룹, 사용자가 맡는 역할, 리소스에 연결할 수 있습니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 IAM에서 정책을 관리합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.IAM` 클라이언트 클래스의 다음 메서드를 사용하여 정책을 생성하고 삭제하며 역할 정책을 연결하고 분리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#createPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#createPolicy-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#getPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#getPolicy-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#listAttachedRolePolicies-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#listAttachedRolePolicies-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#attachRolePolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#attachRolePolicy-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#detachRolePolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#detachRolePolicy-property)

IAM 사용자에 대한 자세한 내용은 *IAM 사용 설명서*에서 [액세스 관리 개요: 권한 및 정책](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_access-management.html)을 참조하세요.

## 사전 필수 작업
<a name="iam-examples-policies-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ 정책을 연결할 수 있는 IAM 역할을 생성합니다. IAM 역할 생성에 대한 자세한 내용은 *IAM 사용 설명서*의 [IAM 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)을 참조하세요.

## IAM 정책 생성
<a name="iam-examples-policies-creating"></a>

파일 이름이 `iam_createpolicy.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 두 개의 JSON 객체를 생성합니다. 하나는 생성하려는 정책 문서를 포함하고 다른 하나는 정책 JSON과 정책에 지정할 이름을 포함하여 정책을 생성하는 데 필요한 파라미터를 포함합니다. 파라미터에서 정책 JSON 객체를 문자열로 만들어야 합니다. `createPolicy` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var myManagedPolicy = {
  Version: "2012-10-17",
  Statement: [
    {
      Effect: "Allow",
      Action: "logs:CreateLogGroup",
      Resource: "RESOURCE_ARN",
    },
    {
      Effect: "Allow",
      Action: [
        "dynamodb:DeleteItem",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Scan",
        "dynamodb:UpdateItem",
      ],
      Resource: "RESOURCE_ARN",
    },
  ],
};

var params = {
  PolicyDocument: JSON.stringify(myManagedPolicy),
  PolicyName: "myDynamoDBPolicy",
};

iam.createPolicy(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_createpolicy.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_createpolicy.js)에서 찾을 수 있습니다.

## IAM 정책 가져오기
<a name="iam-examples-policies-getting"></a>

파일 이름이 `iam_getpolicy.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 정책을 검색하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 가져오려는 정책의 ARN이 포함됩니다. `getPolicy` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다. 정책 설명을 콘솔에 씁니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  PolicyArn: "arn:aws:iam::aws:policy/AWSLambdaExecute",
};

iam.getPolicy(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Policy.Description);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_getpolicy.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_getpolicy.js)에서 찾을 수 있습니다.

## 관리형 역할 정책 연결
<a name="iam-examples-policies-attaching-role-policy"></a>

파일 이름이 `iam_attachrolepolicy.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 역할에 연결된 관리형 IAM 정책의 목록을 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체는 역할의 이름으로 구성됩니다. 역할 이름을 명령줄 파라미터로 제공합니다. `listAttachedRolePolicies` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다. 그러면 관리형 정책 배열이 콜백 함수에 반환됩니다.

배열 구성원을 점검하여 역할에 연결하려는 정책이 이미 연결되어 있는지 확인합니다. 정책이 연결되어 있지 않은 경우 `attachRolePolicy` 메서드를 호출하여 정책을 연결합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var paramsRoleList = {
  RoleName: process.argv[2],
};

iam.listAttachedRolePolicies(paramsRoleList, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var myRolePolicies = data.AttachedPolicies;
    myRolePolicies.forEach(function (val, index, array) {
      if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") {
        console.log(
          "AmazonDynamoDBFullAccess is already attached to this role."
        );
        process.exit();
      }
    });
    var params = {
      PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",
      RoleName: process.argv[2],
    };
    iam.attachRolePolicy(params, function (err, data) {
      if (err) {
        console.log("Unable to attach policy to role", err);
      } else {
        console.log("Role attached successfully");
      }
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_attachrolepolicy.js IAM_ROLE_NAME
```

## 관리형 역할 정책 분리
<a name="iam-examples-policies-detaching-role-policy"></a>

파일 이름이 `iam_detachrolepolicy.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 역할에 연결된 관리형 IAM 정책의 목록을 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체는 역할의 이름으로 구성됩니다. 역할 이름을 명령줄 파라미터로 제공합니다. `listAttachedRolePolicies` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다. 그러면 관리형 정책 배열이 콜백 함수에서 반환됩니다.

배열 구성원을 점검하여 역할에서 분리하려는 정책이 연결되어 있는지 확인합니다. 정책이 연결되어 있는 경우 `detachRolePolicy` 메서드를 호출하여 정책을 분리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var paramsRoleList = {
  RoleName: process.argv[2],
};

iam.listAttachedRolePolicies(paramsRoleList, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var myRolePolicies = data.AttachedPolicies;
    myRolePolicies.forEach(function (val, index, array) {
      if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") {
        var params = {
          PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",
          RoleName: process.argv[2],
        };
        iam.detachRolePolicy(params, function (err, data) {
          if (err) {
            console.log("Unable to detach policy from role", err);
          } else {
            console.log("Policy detached from role successfully");
            process.exit();
          }
        });
      }
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_detachrolepolicy.js IAM_ROLE_NAME
```

# IAM 액세스 키 관리
<a name="iam-examples-managing-access-keys"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 사용자의 액세스 키를 관리하는 방법.

## 시나리오
<a name="iam-examples-managing-access-keys-scenario"></a>

사용자가 SDK for JavaScript에서 AWS를 프로그래밍 방식으로 호출하려면 사용자 고유의 액세스 키가 필요합니다. 이 요구를 충족하기 위해 IAM 사용자에 대한 액세스 키(액세스 키 ID 및 보안 액세스 키)를 생성, 수정, 확인 또는 교체할 수 있습니다. 기본적으로 액세스 키를 생성할 때 액세스 키의 상태는 `Active`이므로 사용자는 액세스 키를 API 호출에 사용할 수 있습니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 IAM에서 액세스 키를 관리합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.IAM` 클라이언트 클래스의 다음 메서드를 사용하여 IAM 액세스 키를 관리합니다.
+ [createAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#createAccessKey-property)
+ [listAccessKeys](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#listAccessKeys-property)
+ [getAccessKeyLastUsed](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#getAccessKeyLastUsed-property)
+ [updateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#updateAccessKey-property)
+ [deleteAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#deleteAccessKey-property)

IAM 액세스 키에 대한 자세한 내용은 *IAM 사용 설명서*의 [액세스 키](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)를 참조하세요.

## 사전 필수 작업
<a name="iam-examples-managing-access-keys-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 사용자를 위한 액세스 키 생성
<a name="iam-examples-managing-access-keys-creating"></a>

파일 이름이 `iam_createaccesskeys.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 새 액세스 키를 생성하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 IAM 사용자의 이름이 포함됩니다. `createAccessKey` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.createAccessKey({ UserName: "IAM_USER_NAME" }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.AccessKey);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. 한 번만 제공할 수 있는 보안 키를 잃어버리지 않도록 반환된 데이터를 텍스트 파일에 파이프해야 합니다.

```
node iam_createaccesskeys.js > newuserkeys.txt
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_createaccesskeys.js)에서 찾을 수 있습니다.

## 사용자의 액세스 키 목록 표시
<a name="iam-examples-managing-access-keys-listing"></a>

파일 이름이 `iam_listaccesskeys.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 사용자의 액세스 키를 검색하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 IAM 사용자의 이름과 목록에 표시할 액세스 키 페어의 최대 수(선택 사항)가 포함됩니다. `listAccessKeys` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  MaxItems: 5,
  UserName: "IAM_USER_NAME",
};

iam.listAccessKeys(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_listaccesskeys.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_listaccesskeys.js)에서 찾을 수 있습니다.

## 액세스 키의 최종 사용 가져오기
<a name="iam-examples-managing-access-keys-last-used"></a>

파일 이름이 `iam_accesskeylastused.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 새 액세스 키를 생성하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 최종 사용 정보가 필요한 액세스 키 ID가 포함됩니다. `getAccessKeyLastUsed` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.getAccessKeyLastUsed(
  { AccessKeyId: "ACCESS_KEY_ID" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data.AccessKeyLastUsed);
    }
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_accesskeylastused.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_accesskeylastused.js)에서 찾을 수 있습니다.

## 액세스 키 상태 업데이트
<a name="iam-examples-managing-access-keys-updating"></a>

파일 이름이 `iam_updateaccesskey.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 액세스 키의 상태를 업데이트하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 액세스 키 ID와 업데이트된 상태가 포함됩니다. 상태는 `Active` 또는 `Inactive`일 수 있습니다. `updateAccessKey` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  AccessKeyId: "ACCESS_KEY_ID",
  Status: "Active",
  UserName: "USER_NAME",
};

iam.updateAccessKey(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_updateaccesskey.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_updateaccesskey.js)에서 찾을 수 있습니다.

## 액세스 키 삭제
<a name="iam-examples-managing-access-keys-deleting"></a>

파일 이름이 `iam_deleteaccesskey.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 액세스 키를 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 액세스 키 ID와 사용자의 이름이 포함됩니다. `deleteAccessKey` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  AccessKeyId: "ACCESS_KEY_ID",
  UserName: "USER_NAME",
};

iam.deleteAccessKey(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_deleteaccesskey.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_deleteaccesskey.js)에서 찾을 수 있습니다.

# IAM 서버 인증서 작업
<a name="iam-examples-server-certificates"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ HTTPS 연결을 위해 서버 인증서를 관리하는 기본 작업을 수행하는 방법.

## 시나리오
<a name="iam-examples-server-certificates-scenario"></a>

AWS에서 웹 사이트나 애플리케이션에 대한 HTTPS 연결을 활성화하려면 SSL/TLS *서버 인증서*가 필요합니다. 외부 공급자에게서 얻은 인증서를 AWS의 웹 사이트 또는 애플리케이션에서 사용하려면 해당 인증서를 IAM에 업로드하거나 AWS Certificate Manager로 가져와야 합니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 IAM에서 서버 인증서를 처리합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.IAM` 클라이언트 클래스의 다음 메서드를 사용하여 서버 인증서를 관리합니다.
+ [listServerCertificates](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#listServerCertificates-property)
+ [getServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#getServerCertificate-property)
+ [updateServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#updateServerCertificate-property)
+ [deleteServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#deleteServerCertificate-property)

IAM의 서버 인증서에 대한 자세한 내용은 *IAM 사용 설명서*의 [서버 인증서 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)을 참조하세요.

## 사전 필수 작업
<a name="iam-examples-server-certificates-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 서버 인증서 목록 표시
<a name="iam-examples-server-certificates-listing"></a>

파일 이름이 `iam_listservercerts.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. `listServerCertificates` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.listServerCertificates({}, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_listservercerts.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_listservercerts.js)에서 찾을 수 있습니다.

## 서버 인증서 가져오기
<a name="iam-examples-server-certificates-getting"></a>

파일 이름이 `iam_getservercert.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 인증서를 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체는 원하는 서버 인증서의 이름으로 구성됩니다. `getServerCertificates` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.getServerCertificate(
  { ServerCertificateName: "CERTIFICATE_NAME" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_getservercert.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_getservercert.js)에서 찾을 수 있습니다.

## 서버 인증서 업데이트
<a name="iam-examples-server-certificates-updating"></a>

파일 이름이 `iam_updateservercert.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 인증서를 업데이트하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체는 기존 서버 인증서의 이름과 새 인증서의 이름으로 구성됩니다. `updateServerCertificate` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  ServerCertificateName: "CERTIFICATE_NAME",
  NewServerCertificateName: "NEW_CERTIFICATE_NAME",
};

iam.updateServerCertificate(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_updateservercert.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_updateservercert.js)에서 찾을 수 있습니다.

## 서버 인증서 삭제
<a name="iam-examples-server-certificates-deleting"></a>

파일 이름이 `iam_deleteservercert.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 서버 인증서를 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체는 삭제하려는 인증서의 이름으로 구성됩니다. `deleteServerCertificates` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.deleteServerCertificate(
  { ServerCertificateName: "CERTIFICATE_NAME" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_deleteservercert.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_deleteservercert.js)에서 찾을 수 있습니다.

# IAM 계정 별칭 관리
<a name="iam-examples-account-aliases"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ AWS 계정 ID의 별칭을 관리하는 방법

## 시나리오
<a name="iam-examples-account-aliases-scenario"></a>

AWS 계정 ID 대신 회사 이름이나 기타 친숙한 식별자를 로그인 페이지의 URL에 포함하려는 경우 AWS 계정 ID의 별칭을 만들 수 있습니다. AWS 계정 별칭을 생성할 경우 명칭을 적용하기 위해 로그인 페이지 URL이 변경됩니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 IAM 계정 별칭을 생성하고 관리합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.IAM` 클라이언트 클래스의 다음 메서드를 사용하여 별칭을 관리합니다.
+ [createAccountAlias](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#createAccountAlias-property)
+ [listAccountAliases](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#listAccountAliases-property)
+ [deleteAccountAlias](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/IAM.html#deleteAccountAlias-property)

IAM 계정 별칭에 대한 자세한 내용은 AWS 계정 ID 및 별칭을 참조하세요.

## 사전 필수 작업
<a name="iam-examples-account-aliases-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 계정 별칭 생성
<a name="iam-examples-account-aliases-creating"></a>

파일 이름이 `iam_createaccountalias.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 계정 별칭을 생성하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 생성하려는 별칭이 포함됩니다. `createAccountAlias` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.createAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_createaccountalias.js ALIAS
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_createaccountalias.js)에서 찾을 수 있습니다.

## 계정 별칭 나열
<a name="iam-examples-account-aliases-listing"></a>

파일 이름이 `iam_listaccountaliases.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 계정 별칭 목록을 표시하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 반환할 항목의 최대 수가 포함되어 있습니다. `listAccountAliases` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.listAccountAliases({ MaxItems: 10 }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_listaccountaliases.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_listaccountaliases.js)에서 찾을 수 있습니다.

## 계정 별칭 삭제
<a name="iam-examples-account-aliases-deleting"></a>

파일 이름이 `iam_deleteaccountalias.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. IAM에 액세스하려면 `AWS.IAM` 서비스 객체를 생성합니다. 계정 별칭을 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 삭제하려는 별칭이 포함됩니다. `deleteAccountAlias` 서비스 객체의 `AWS.IAM` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.deleteAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node iam_deleteaccountalias.js ALIAS
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/iam/iam_deleteaccountalias.js)에서 찾을 수 있습니다.

# Amazon Kinesis 예제
<a name="kinesis-examples"></a>

Amazon Kinesis는 AWS의 스트리밍 데이터를 위한 플랫폼으로, 스트리밍 데이터를 로드하고 분석하기 위한 강력한 서비스를 제공하며 전문화된 요구에 맞게 사용자 지정 스트리밍 데이터 애플리케이션을 빌드할 수 있는 기능도 제공합니다.

![\[JavaScript 환경, AWS SDK, Kinesis 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-kinesis.png)


Kinesis용 JavaScript API는 `AWS.Kinesis` 클라이언트 클래스를 통해 노출됩니다. Kinesis 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Kinesis.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Kinesis.html) 섹션을 참조하세요.

**Topics**
+ [Amazon Kinesis를 사용하여 웹 페이지 스크롤 진행 상황 캡처](kinesis-examples-capturing-page-scrolling.md)

# Amazon Kinesis를 사용하여 웹 페이지 스크롤 진행 상황 캡처
<a name="kinesis-examples-capturing-page-scrolling"></a>

![\[JavaScript code example that applies to browser execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/browsericon.png)

**이 브라우저 스크립트 예제는 다음을 보여 줍니다.**
+ 추후 분석을 위한 스트리밍 페이지 사용 지표의 예로 Amazon Kinesis를 사용하여 웹 페이지에서 스크롤 진행 상황을 캡처하는 방법

## 시나리오
<a name="kinesis-examples-capturing-page-scrolling-scenario"></a>

이 예제에서는 단순 HTML 페이지에서 블로그 페이지의 콘텐츠를 시뮬레이션합니다. 독자가 시뮬레이션된 블로그 게시물을 스크롤하면 브라우저 스크립트는 SDK for JavaScript로 Kinesis 클라이언트 클래스의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Kinesis.html#putRecords-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Kinesis.html#putRecords-property) 메서드를 사용하여 페이지 아래쪽 스크롤 거리를 기록하고 해당 데이터를 Kinesis에 전송합니다. 그러면 Amazon Kinesis Data Streams에서 캡처한 스트리밍 데이터를 Amazon EC2 인스턴스에서 처리하고 Amazon DynamoDB 및 Amazon Redshift를 포함한 여러 데이터 스토어에 저장할 수 있습니다.

## 사전 필수 작업
<a name="kinesis-examples-capturing-page-scrolling-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Kinesis 스트림 생성 스트림의 리소스 ARN을 브라우저 스크립트에 포함시켜야 합니다. 자세한 내용은 *Amazon Kinesis Data Streams 개발자 안내서*의 [Kinesis Streams란?](https://docs.aws.amazon.com/streams/latest/dev/working-with-streams.html)을 참조하세요.
+ 인증되지 않은 자격 증명에 대해 활성화된 액세스 권한이 있는 Amazon Cognito 자격 증명 풀 브라우저 스크립트에 대한 자격 증명을 획득하려면 자격 증명 풀 ID를 코드에 포함시켜야 합니다. Amazon Cognito 자격 증명 풀에 관한 자세한 내용은 *Amazon Cognito 개발자 안내서*의 [자격 증명 풀](https://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html)을 참조하세요.
+ 데이터를 Kinesis 스트림에 제출할 수 있는 권한을 부여하는 정책이 있는 Kinesis 역할을 생성합니다. IAM 역할 생성에 관한 자세한 내용은 *IAM 사용 설명서*의 [AWS 서비스에 대한 권한을 위임할 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) 섹션을 참조하세요.

IAM 역할을 생성할 때 다음 역할 정책을 사용합니다.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Action": [
            "mobileanalytics:PutEvents",
            "cognito-sync:*"
         ],
         "Resource": [
            "*"
         ]
      },
      {
         "Effect": "Allow",
         "Action": [
            "kinesis:Put*"
         ],
         "Resource": [
            "arn:aws:kinesis:us-east-1:111122223333:stream/stream-name"
         ]
      }
   ]
}
```

------

## 블로그 페이지
<a name="kinesis-examples-capturing-page-scrolling-html"></a>

블로그 페이지용 HTML은 주로 `<div>` 요소 내에 포함된 일련의 단락으로 구성됩니다. 이 `<div>`의 스크롤 가능한 높이는 독자가 필요에 따라 콘텐츠를 스크롤한 거리를 계산하는 데 사용됩니다. HTML에는 `<script>` 요소 페어도 포함됩니다. 이러한 요소 중 하나는 SDK for JavaScript를 페이지에 추가하고 다른 하나는 페이지에서 스크롤 진행 상황을 캡처하여 Kinesis에 보고하는 브라우저 스크립트를 추가합니다.

```
<!DOCTYPE html>
<html>
    <head>
        <title>AWS SDK for JavaScript - Amazon Kinesis Application</title>
    </head>
    <body>
        <div id="BlogContent" style="width: 60%; height: 800px; overflow: auto;margin: auto; text-align: center;">
            <div>
                <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae nulla eget nisl bibendum feugiat. Fusce rhoncus felis at ultricies luctus. Vivamus fermentum cursus sem at interdum. Proin vel lobortis nulla. Aenean rutrum odio in tellus semper rhoncus. Nam eu felis ac augue dapibus laoreet vel in erat. Vivamus vitae mollis turpis. Integer sagittis dictum odio. Duis nec sapien diam. In imperdiet sem nec ante laoreet, vehicula facilisis sem placerat. Duis ut metus egestas, ullamcorper neque et, accumsan quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
                </p>
                <!-- Additional paragraphs in the blog page appear here -->
            </div>
        </div>
        <script src="https://sdk.amazonaws.com/js/aws-sdk-2.283.1.min.js"></script>
        <script src="kinesis-example.js"></script>
    </body>
</html>
```

## SDK 구성
<a name="kinesis-examples-capturing-page-scrolling-configure-sdk"></a>

Amazon Cognito 자격 증명 풀 ID를 제공하는 `CognitoIdentityCredentials` 메서드를 직접 호출하여 SDK를 구성하는 데 필요한 자격 증명을 획득합니다. 성공하면 콜백 함수에서 Kinesis 서비스 객체를 생성합니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [웹 페이지 스크롤 진행 상황 코드 캡처](kinesis-examples-capturing-page-scrolling-full.md) 섹션을 참조하세요.)

```
// Configure Credentials to use Cognito
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: "IDENTITY_POOL_ID",
});

AWS.config.region = "REGION";
// We're going to partition Amazon Kinesis records based on an identity.
// We need to get credentials first, then attach our event listeners.
AWS.config.credentials.get(function (err) {
  // attach event listener
  if (err) {
    alert("Error retrieving credentials.");
    console.error(err);
    return;
  }
  // create Amazon Kinesis service object
  var kinesis = new AWS.Kinesis({
    apiVersion: "2013-12-02",
  });
```

## 스크롤 레코드 생성
<a name="kinesis-examples-capturing-page-scrolling-create-records"></a>

스크롤 진행 상황은 블로그 게시물의 콘텐츠를 포함하는 `scrollHeight`의 `scrollTop` 및 `<div>` 속성을 사용하여 계산됩니다. 각 스크롤 레코드는 `scroll` 이벤트에 대한 이벤트 리스너 함수에서 생성된 다음, Kinesis에 정기적으로 제출하기 위한 레코드 배열에 추가됩니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [웹 페이지 스크롤 진행 상황 코드 캡처](kinesis-examples-capturing-page-scrolling-full.md) 섹션을 참조하세요.)

```
  // Get the ID of the Web page element.
  var blogContent = document.getElementById("BlogContent");

  // Get Scrollable height
  var scrollableHeight = blogContent.clientHeight;

  var recordData = [];
  var TID = null;
  blogContent.addEventListener("scroll", function (event) {
    clearTimeout(TID);
    // Prevent creating a record while a user is actively scrolling
    TID = setTimeout(function () {
      // calculate percentage
      var scrollableElement = event.target;
      var scrollHeight = scrollableElement.scrollHeight;
      var scrollTop = scrollableElement.scrollTop;

      var scrollTopPercentage = Math.round((scrollTop / scrollHeight) * 100);
      var scrollBottomPercentage = Math.round(
        ((scrollTop + scrollableHeight) / scrollHeight) * 100
      );

      // Create the Amazon Kinesis record
      var record = {
        Data: JSON.stringify({
          blog: window.location.href,
          scrollTopPercentage: scrollTopPercentage,
          scrollBottomPercentage: scrollBottomPercentage,
          time: new Date(),
        }),
        PartitionKey: "partition-" + AWS.config.credentials.identityId,
      };
      recordData.push(record);
    }, 100);
  });
```

## Kinesis에 레코드 제출
<a name="kinesis-examples-capturing-page-scrolling-submit-records"></a>

배열에 레코드가 있는 경우 1초에 한 번씩 해당 보류 레코드가 Kinesis에 전송됩니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [웹 페이지 스크롤 진행 상황 코드 캡처](kinesis-examples-capturing-page-scrolling-full.md) 섹션을 참조하세요.)

```
  // upload data to Amazon Kinesis every second if data exists
  setInterval(function () {
    if (!recordData.length) {
      return;
    }
    // upload data to Amazon Kinesis
    kinesis.putRecords(
      {
        Records: recordData,
        StreamName: "NAME_OF_STREAM",
      },
      function (err, data) {
        if (err) {
          console.error(err);
        }
      }
    );
    // clear record data
    recordData = [];
  }, 1000);
});
```

# 웹 페이지 스크롤 진행 상황 코드 캡처
<a name="kinesis-examples-capturing-page-scrolling-full"></a>

다음은 웹 페이지 스크롤 진행 상황 예제를 캡처하는 Kinesis용 브라우저 스크립트 코드입니다.

```
// Configure Credentials to use Cognito
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: "IDENTITY_POOL_ID",
});

AWS.config.region = "REGION";
// We're going to partition Amazon Kinesis records based on an identity.
// We need to get credentials first, then attach our event listeners.
AWS.config.credentials.get(function (err) {
  // attach event listener
  if (err) {
    alert("Error retrieving credentials.");
    console.error(err);
    return;
  }
  // create Amazon Kinesis service object
  var kinesis = new AWS.Kinesis({
    apiVersion: "2013-12-02",
  });

  // Get the ID of the Web page element.
  var blogContent = document.getElementById("BlogContent");

  // Get Scrollable height
  var scrollableHeight = blogContent.clientHeight;

  var recordData = [];
  var TID = null;
  blogContent.addEventListener("scroll", function (event) {
    clearTimeout(TID);
    // Prevent creating a record while a user is actively scrolling
    TID = setTimeout(function () {
      // calculate percentage
      var scrollableElement = event.target;
      var scrollHeight = scrollableElement.scrollHeight;
      var scrollTop = scrollableElement.scrollTop;

      var scrollTopPercentage = Math.round((scrollTop / scrollHeight) * 100);
      var scrollBottomPercentage = Math.round(
        ((scrollTop + scrollableHeight) / scrollHeight) * 100
      );

      // Create the Amazon Kinesis record
      var record = {
        Data: JSON.stringify({
          blog: window.location.href,
          scrollTopPercentage: scrollTopPercentage,
          scrollBottomPercentage: scrollBottomPercentage,
          time: new Date(),
        }),
        PartitionKey: "partition-" + AWS.config.credentials.identityId,
      };
      recordData.push(record);
    }, 100);
  });

  // upload data to Amazon Kinesis every second if data exists
  setInterval(function () {
    if (!recordData.length) {
      return;
    }
    // upload data to Amazon Kinesis
    kinesis.putRecords(
      {
        Records: recordData,
        StreamName: "NAME_OF_STREAM",
      },
      function (err, data) {
        if (err) {
          console.error(err);
        }
      }
    );
    // clear record data
    recordData = [];
  }, 1000);
});
```

# Amazon S3 예제
<a name="s3-examples"></a>

Amazon Simple Storage Service(S3)는 확장성이 뛰어난 클라우드 스토리지를 제공하는 웹 서비스입니다. Amazon S3는 웹 어디에서나 원하는 양의 데이터를 저장하고 검색할 수 있는 간단한 웹 서비스 인터페이스를 갖춘 사용하기 쉬운 객체 스토리지입니다.

![\[JavaScript 환경, SDK, Amazon S3 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-s3.png)


Amazon S3용 JavaScript API는 `AWS.S3` 클라이언트 클래스를 통해 노출됩니다. Amazon S3 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html) 섹션을 참조하세요.

**Topics**
+ [Amazon S3 브라우저 예제](s3-browser-examples.md)
+ [Amazon S3 Node.js 예제](s3-node-examples.md)

# Amazon S3 브라우저 예제
<a name="s3-browser-examples"></a>

다음 주제는 브라우저에서 Amazon S3 버킷과의 상호 작용을 위해 AWS SDK for JavaScript가 사용되는 방식의 예제 두 가지를 설명합니다.
+ 첫 번째 예제는 Amazon S3 버킷의 기존 사진은 모든 (미인증) 사용자가 볼 수 있는 단순한 시나리오를 보여줍니다.
+ 두 번째 예제는 더욱 복잡한 시나리오로 사용자가 버킷의 사진에 대해 업로드, 삭제 등의 작업을 수행할 수 있습니다.

**Topics**
+ [브라우저에서 Amazon S3 버킷의 사진 보기](s3-example-photos-view.md)
+ [브라우저에서 Amazon S3에 사진 업로드](s3-example-photo-album.md)

# 브라우저에서 Amazon S3 버킷의 사진 보기
<a name="s3-example-photos-view"></a>

![\[JavaScript code example that applies to browser execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/browsericon.png)

**이 브라우저 스크립트 코드 예제는 다음을 보여 줍니다.**
+ Amazon Simple Storage Service(S3) 버킷에서 사진 앨범을 생성하고 미인증 사용자가 사진을 볼 수 있도록 허용하는 방법

## 시나리오
<a name="s3-example-photos-view-scenario"></a>

이 예제에서는 단순한 HTML 페이지를 통해 사진 앨범의 사진을 볼 수 있는 브라우저 기반 애플리케이션이 제공됩니다. 사진 앨범은 사진이 업로드되는 Amazon S3 버킷에 있습니다.

![\[사진 앨범에 Amazon S3 버킷을 사용하는 브라우저 스크립트의 JavaScript\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/s3-photo-album-example.png)


브라우저 스크립트는 SDK for JavaScript를 사용하여 Amazon S3 버킷과 상호 작용합니다. 스크립트는 Amazon S3 클라이언트 클래스의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property) 메서드를 사용하여 사진 앨범을 볼 수 있게 합니다.

## 사전 필수 작업
<a name="s3-example-photos-view-scenario-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.

**참고**  
이 예제에서는 Amazon S3 버킷과 Amazon Cognito 자격 증명 풀에 대해 동일한 AWS 리전을 사용해야 합니다.

### 버킷 생성
<a name="s3-example-photos-view-prereq-bucket"></a>

[Amazon S3 콘솔](https://console.aws.amazon.com/s3/)에서 앨범과 사진을 저장할 수 있는 Amazon S3 버킷을 생성합니다. 콘솔을 사용한 S3 버킷 생성에 대한 자세한 내용을 알아보려면 *Amazon Simple Storage Service 사용 설명서*의 [버킷 생성](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket.html)을 참조하세요.

S3 버킷 생성 시에는 다음을 수행합니다.
+ 후속 사전 필수 작업인 역할 권한 구성 시 사용할 수 있도록 버킷 이름을 메모해 둡니다.
+ 버킷을 생성할 AWS 지역을 선택합니다. 후속 사전 필수 작업인 자격 증명 풀 생성 시 Amazon Cognito 자격 증명 풀을 생성하는 데 사용할 리전과 동일한 리전이어야 합니다.
+ **Amazon Simple Storage Service 사용 설명서의 [웹 사이트 액세스에 대한 권한 설정](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteAccessPermissionsReqd.html)을 따라 버킷 권한을 구성합니다.

### 자격 증명 풀 생성
<a name="s3-example-photos-view-prereq-idpool"></a>

*브라우저 스크립트에서 시작하기*의 [1단계: Amazon Cognito 자격 증명 풀 생성](getting-started-browser.md#getting-started-browser-create-identity-pool) 섹션을 참조하여 [Amazon Cognito 콘솔](https://console.aws.amazon.com/cognito/)에서 Amazon Cognito 자격 증명 풀을 생성합니다.

자격 증명 풀을 생성할 때는 **인증되지 않은** 자격 증명의 역할 이름과 자격 증명 풀의 이름을 메모해 둡니다.

### 역할 권한 구성
<a name="s3-example-photos-view-prereq-perms"></a>

앨범 및 사진 보기를 허용하려면 방금 생성한 자격 증명 풀의 IAM 역할에 권한을 추가해야 합니다. 다음과 같이 정책을 생성하며 시작합니다.

1. [IAM 콘솔](https://console.aws.amazon.com/iam/)을 엽니다.

1. 왼쪽 탐색 창에서 **정책**을 선택한 후 **정책 생성** 버튼을 선택합니다.

1. **JSON** 탭에 다음의 JSON 정의를 입력하되, *BUCKET\$1NAME*은 버킷 이름으로 대체합니다.

------
#### [ JSON ]

****  

   ```
   {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
         {
            "Effect": "Allow",
            "Action": [
               "s3:ListBucket"
            ],
            "Resource": [
               "arn:aws:s3:::BUCKET_NAME"
            ]
         }
      ]
   }
   ```

------

1. **정책 검토** 버튼을 선택하고 정책 이름을 지정한 다음 설명을 입력하고(원할 경우), **정책 생성** 버튼을 선택합니다.

   나중에 찾아서 IAM 역할에 연결할 수 있도록 이름을 메모해 둡니다.

정책이 생성되면 [IAM 콘솔](https://console.aws.amazon.com/iam/)로 돌아갑니다. 이전 사전 필수 작업인 자격 증명 풀 생성에서 Amazon Cognito가 생성한 **미인증** 자격 증명의 IAM 역할을 찾습니다. 방금 생성한 정책을 사용하여 이 자격 증명에 권한을 추가합니다.

이 작업의 워크플로는 일반적으로 *브라우저 스크립트에서 시작하기*의 [2단계: 생성된 IAM 역할에 정책 추가](getting-started-browser.md#getting-started-browser-iam-role) 섹션과 동일하지만 몇 가지 차이점이 있습니다.
+ Amazon Polly에 대한 정책이 아닌 방금 생성한 새로운 정책을 사용합니다.
+ **권한 연결** 페이지에서 새로운 정책을 빠르게 찾아 보려면 **필터 정책** 목록을 열고 **고객 관리형**을 선택합니다.

IAM 역할 생성에 관한 추가 정보는 *IAM 사용 설명서*의 [AWS 서비스에 대한 권한을 위임할 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) 섹션을 참조하세요.

### CORS 구성
<a name="s3-example-photos-view-cors-configuration"></a>

브라우저 스크립트가 Amazon 버킷에 액세스하려면 다음과 같이 [CORS 구성](cors.md#configuring-cors-s3-bucket)을 설정해야 합니다.

**중요**  
새 S3 콘솔에서 CORS 구성은 JSON이어야 합니다.

------
#### [ JSON ]

```
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "HEAD",
            "GET"
        ],
        "AllowedOrigins": [
            "*"
        ]
    }
]
```

------
#### [ XML ]

```
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
```

------

### 앨범 생성 및 사진 업로드
<a name="s3-example-photos-view-create-albums"></a>

이 예제에서는 사용자가 이미 버킷에 있는 사진만 볼 수 있기 때문에 버킷에 앨범을 생성하고 그 앨범으로 사진을 업로드해야 합니다.

**참고**  
이 예제의 경우, 사진 파일의 파일명은 하나의 밑줄("\$1")로 시작해야 합니다. 이 문자는 나중에 필터링하는 데 중요합니다. 또한, 사진 소유자의 저작권을 존중해 주십시오.

1. [Amazon S3 콘솔](https://console.aws.amazon.com/s3/)에서 앞서 생성한 버킷을 엽니다.

1. **개요** 탭에서 **폴더 만들기** 버튼을 선택하여 폴더를 생성합니다. 이 예제에서는 폴더명을 "album1", "album2" 및 "album3"으로 지정합니다.

1. **album1**과 **album2**에 대해 폴더를 선택한 다음 다음과 같이 사진을 업로드합니다.

   1. **업로드** 버튼을 선택합니다.

   1. 사용할 사진 파일을 끌거나 선택하고 **다음**을 선택합니다.

   1. **퍼블릭 권한 관리**에서 **이 객체에 퍼블릭 읽기 액세스 권한을 부여함**을 선택합니다.

   1. **업로드** 버튼(왼쪽 아래 모서리)을 선택합니다.

1. **album3**은 비워둡니다.

## 웹페이지 정의
<a name="s3-example-photos-view-html"></a>

사진 보기 애플리케이션을 위한 HTML은 브라우저 스크립트가 보기 인터페이스를 생성하는 `<div>` 요소로 구성됩니다. 첫 번째 `<script>` 요소는 SDK를 브라우저 스크립트에 추가합니다. 두 번째 `<script>` 요소는 브라우저 스크립트 코드를 담는 외부 JavaScript 파일을 추가합니다.

이 예제에서는 파일명이 `PhotoViewer.js`로 지정되었으며 HTML 파일과 동일한 폴더에 위치합니다. [AWS SDK for JavaScript API 참조 가이드](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/)의 SDK for JavaScript에 대한 API 참조 섹션에서 현재 SDK\$1VERSION\$1NUMBER를 찾을 수 있습니다.

```
<!DOCTYPE html>
<html>
  <head>
    <!-- **DO THIS**: -->
    <!--   Replace SDK_VERSION_NUMBER with the current SDK version number -->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.js"></script>
    <script src="./PhotoViewer.js"></script>
    <script>listAlbums();</script>
  </head>
  <body>
    <h1>Photo Album Viewer</h1>
    <div id="viewer" />
  </body>
</html>
```



## SDK 구성
<a name="s3-example-photos-view-config"></a>

`CognitoIdentityCredentials` 메서드를 호출하여 SDK를 구성하는 데 필요한 자격 증명을 획득합니다. Amazon Cognito 자격 증명 풀 ID를 제공해야 합니다. 그런 다음, `AWS.S3` 서비스 객체를 생성합니다.

```
// **DO THIS**:
//   Replace BUCKET_NAME with the bucket name.
//
var albumBucketName = "BUCKET_NAME";

// **DO THIS**:
//   Replace this block of code with the sample code located at:
//   Cognito -- Manage Identity Pools -- [identity_pool_name] -- Sample Code -- JavaScript
//
// Initialize the Amazon Cognito credentials provider
AWS.config.region = "REGION"; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: "IDENTITY_POOL_ID",
});

// Create a new service object
var s3 = new AWS.S3({
  apiVersion: "2006-03-01",
  params: { Bucket: albumBucketName },
});

// A utility function to create HTML.
function getHtml(template) {
  return template.join("\n");
}
```

이 예제에 있는 코드의 나머지 부분은 버킷의 앨범과 사진에 관한 정보를 수집 및 제공하기 위해 다음의 함수를 정의합니다.
+ `listAlbums`
+ `viewAlbum`

## 버킷에 있는 앨범 목록 표시
<a name="s3-example-photos-view-list-albums"></a>

버킷에 있는 모든 앨범의 목록을 표시하기 위해 애플리케이션의 `listAlbums` 함수는 `listObjects` 서비스 객체의 `AWS.S3` 메서드를 호출합니다. 이 함수는 `CommonPrefixes` 속성을 사용하므로 이 호출은 앨범으로 사용된 객체(폴더)만 반환합니다.

이 함수의 나머지 부분은 Amazon S3 버킷에서 앨범 목록을 가져오고 웹 페이지에 앨범 목록을 표시하는 데 필요한 HTML을 생성합니다.

```
// List the photo albums that exist in the bucket.
function listAlbums() {
  s3.listObjects({ Delimiter: "/" }, function (err, data) {
    if (err) {
      return alert("There was an error listing your albums: " + err.message);
    } else {
      var albums = data.CommonPrefixes.map(function (commonPrefix) {
        var prefix = commonPrefix.Prefix;
        var albumName = decodeURIComponent(prefix.replace("/", ""));
        return getHtml([
          "<li>",
          '<button style="margin:5px;" onclick="viewAlbum(\'' +
            albumName +
            "')\">",
          albumName,
          "</button>",
          "</li>",
        ]);
      });
      var message = albums.length
        ? getHtml(["<p>Click on an album name to view it.</p>"])
        : "<p>You do not have any albums. Please Create album.";
      var htmlTemplate = [
        "<h2>Albums</h2>",
        message,
        "<ul>",
        getHtml(albums),
        "</ul>",
      ];
      document.getElementById("viewer").innerHTML = getHtml(htmlTemplate);
    }
  });
}
```

## 앨범 보기
<a name="s3-example-photos-view-viewing-album"></a>

Amazon S3 버킷에 앨범의 콘텐츠를 표시하기 위해 애플리케이션의 `viewAlbum` 함수는 앨범 이름을 가져오고 해당 앨범에 대한 Amazon S3 키를 생성합니다. 그런 다음 이 함수는 `listObjects` 서비스 객체의 `AWS.S3` 메서드를 호출하여 앨범에 있는 모든 객체(사진)의 목록을 획득합니다.

이 함수의 나머지 부분은 앨범에 있는 객체 목록을 가져오고 웹 페이지에 사진을 표시하는 데 필요한 HTML을 생성합니다.

```
// Show the photos that exist in an album.
function viewAlbum(albumName) {
  var albumPhotosKey = encodeURIComponent(albumName) + "/";
  s3.listObjects({ Prefix: albumPhotosKey }, function (err, data) {
    if (err) {
      return alert("There was an error viewing your album: " + err.message);
    }
    // 'this' references the AWS.Request instance that represents the response
    var href = this.request.httpRequest.endpoint.href;
    var bucketUrl = href + albumBucketName + "/";

    var photos = data.Contents.map(function (photo) {
      var photoKey = photo.Key;
      var photoUrl = bucketUrl + encodeURIComponent(photoKey);
      return getHtml([
        "<span>",
        "<div>",
        "<br/>",
        '<img style="width:128px;height:128px;" src="' + photoUrl + '"/>',
        "</div>",
        "<div>",
        "<span>",
        photoKey.replace(albumPhotosKey, ""),
        "</span>",
        "</div>",
        "</span>",
      ]);
    });
    var message = photos.length
      ? "<p>The following photos are present.</p>"
      : "<p>There are no photos in this album.</p>";
    var htmlTemplate = [
      "<div>",
      '<button onclick="listAlbums()">',
      "Back To Albums",
      "</button>",
      "</div>",
      "<h2>",
      "Album: " + albumName,
      "</h2>",
      message,
      "<div>",
      getHtml(photos),
      "</div>",
      "<h2>",
      "End of Album: " + albumName,
      "</h2>",
      "<div>",
      '<button onclick="listAlbums()">',
      "Back To Albums",
      "</button>",
      "</div>",
    ];
    document.getElementById("viewer").innerHTML = getHtml(htmlTemplate);
    document
      .getElementsByTagName("img")[0]
      .setAttribute("style", "display:none;");
  });
}
```

# Amazon S3 버킷의 사진 보기: 전체 코드
<a name="s3-example-photos-view-full"></a>

이 섹션에는 Amazon S3 버킷의 사진을 볼 수 있는 예제를 위한 HTML 및 JavaScript 전체 코드가 포함되어 있습니다. 자세한 내용과 사전 조건은 [상위 섹션](s3-example-photos-view.md)을 참조하세요.

HTML 예제:

```
<!DOCTYPE html>
<html>
  <head>
    <!-- **DO THIS**: -->
    <!--   Replace SDK_VERSION_NUMBER with the current SDK version number -->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.js"></script>
    <script src="./PhotoViewer.js"></script>
    <script>listAlbums();</script>
  </head>
  <body>
    <h1>Photo Album Viewer</h1>
    <div id="viewer" />
  </body>
</html>
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_PhotoViewer.html)에서 찾을 수 있습니다.

브라우저 스크립트 코드 예제:

```
//
// Data constructs and initialization.
//

// **DO THIS**:
//   Replace BUCKET_NAME with the bucket name.
//
var albumBucketName = "BUCKET_NAME";

// **DO THIS**:
//   Replace this block of code with the sample code located at:
//   Cognito -- Manage Identity Pools -- [identity_pool_name] -- Sample Code -- JavaScript
//
// Initialize the Amazon Cognito credentials provider
AWS.config.region = "REGION"; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId: "IDENTITY_POOL_ID",
});

// Create a new service object
var s3 = new AWS.S3({
  apiVersion: "2006-03-01",
  params: { Bucket: albumBucketName },
});

// A utility function to create HTML.
function getHtml(template) {
  return template.join("\n");
}

//
// Functions
//

// List the photo albums that exist in the bucket.
function listAlbums() {
  s3.listObjects({ Delimiter: "/" }, function (err, data) {
    if (err) {
      return alert("There was an error listing your albums: " + err.message);
    } else {
      var albums = data.CommonPrefixes.map(function (commonPrefix) {
        var prefix = commonPrefix.Prefix;
        var albumName = decodeURIComponent(prefix.replace("/", ""));
        return getHtml([
          "<li>",
          '<button style="margin:5px;" onclick="viewAlbum(\'' +
            albumName +
            "')\">",
          albumName,
          "</button>",
          "</li>",
        ]);
      });
      var message = albums.length
        ? getHtml(["<p>Click on an album name to view it.</p>"])
        : "<p>You do not have any albums. Please Create album.";
      var htmlTemplate = [
        "<h2>Albums</h2>",
        message,
        "<ul>",
        getHtml(albums),
        "</ul>",
      ];
      document.getElementById("viewer").innerHTML = getHtml(htmlTemplate);
    }
  });
}

// Show the photos that exist in an album.
function viewAlbum(albumName) {
  var albumPhotosKey = encodeURIComponent(albumName) + "/";
  s3.listObjects({ Prefix: albumPhotosKey }, function (err, data) {
    if (err) {
      return alert("There was an error viewing your album: " + err.message);
    }
    // 'this' references the AWS.Request instance that represents the response
    var href = this.request.httpRequest.endpoint.href;
    var bucketUrl = href + albumBucketName + "/";

    var photos = data.Contents.map(function (photo) {
      var photoKey = photo.Key;
      var photoUrl = bucketUrl + encodeURIComponent(photoKey);
      return getHtml([
        "<span>",
        "<div>",
        "<br/>",
        '<img style="width:128px;height:128px;" src="' + photoUrl + '"/>',
        "</div>",
        "<div>",
        "<span>",
        photoKey.replace(albumPhotosKey, ""),
        "</span>",
        "</div>",
        "</span>",
      ]);
    });
    var message = photos.length
      ? "<p>The following photos are present.</p>"
      : "<p>There are no photos in this album.</p>";
    var htmlTemplate = [
      "<div>",
      '<button onclick="listAlbums()">',
      "Back To Albums",
      "</button>",
      "</div>",
      "<h2>",
      "Album: " + albumName,
      "</h2>",
      message,
      "<div>",
      getHtml(photos),
      "</div>",
      "<h2>",
      "End of Album: " + albumName,
      "</h2>",
      "<div>",
      '<button onclick="listAlbums()">',
      "Back To Albums",
      "</button>",
      "</div>",
    ];
    document.getElementById("viewer").innerHTML = getHtml(htmlTemplate);
    document
      .getElementsByTagName("img")[0]
      .setAttribute("style", "display:none;");
  });
}
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_PhotoViewer.js)에서 찾을 수 있습니다.

# 브라우저에서 Amazon S3에 사진 업로드
<a name="s3-example-photo-album"></a>

![\[JavaScript code example that applies to browser execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/browsericon.png)

**이 브라우저 스크립트 코드 예제는 다음을 보여 줍니다.**
+ 사용자가 Amazon S3 버킷에서 사진 앨범을 생성하고 해당 앨범으로 사진을 업로드할 수 있도록 브라우저 애플리케이션을 생성하는 방법

## 시나리오
<a name="s3-example-photo-album-scenario"></a>

이 예제에서는 간단한 HTML 페이지에서 사진을 업로드할 수 있는 Amazon S3 버킷의 사진 앨범을 생성하기 위한 브라우저 기반 애플리케이션을 제공합니다. 이 애플리케이션을 사용하여 추가한 사진과 앨범을 삭제할 수 있습니다.

![\[사진 앨범에 Amazon S3 버킷을 사용하는 브라우저 스크립트의 JavaScript\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/s3-photo-album-example.png)


브라우저 스크립트는 SDK for JavaScript를 사용하여 Amazon S3 버킷과 상호 작용합니다. Amazon S3 클라이언트 클래스의 다음 메서드를 사용하여 사진 앨범 애플리케이션을 활성화합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headObject-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headObject-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObject-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObject-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObjects-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObjects-property)

## 사전 필수 작업
<a name="s3-example-photo-album-scenario-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ [Amazon S3 콘솔](https://console.aws.amazon.com/s3/)에서 앨범에 사진을 저장하는 데 사용할 Amazon S3 버킷을 생성합니다. 콘솔 내 버킷 생성에 대한 자세한 내용을 알아보려면 *Amazon Simple Storage Service 사용 설명서*의 [버킷 생성](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket.html)을 참조하세요. **객체**에 대한 **읽기** 및 **쓰기** 권한이 모두 있는지 확인합니다. 버킷 설정 권한에 대한 자세한 내용은 [웹 사이트 액세스 권한 설정](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteAccessPermissionsReqd.html)을 참조하세요.
+ [Amazon Cognito 콘솔](https://console.aws.amazon.com/cognito/)에서 Amazon S3 버킷과 동일한 리전에 있는 미인증 사용자에 대해 활성화된 액세스 권한이 있는 연동 자격 증명을 사용하여 Amazon Cognito 자격 증명 풀을 생성합니다. 브라우저 스크립트에 대한 자격 증명을 획득하려면 자격 증명 풀 ID를 코드에 포함시켜야 합니다. 자세한 내용은 *Amazon Cognito 개발자 안내서*의 [Amazon Cognito 자격 증명 풀(페더레이션 자격 증명)](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html)을 참조하세요.
+ [IAM 콘솔](https://console.aws.amazon.com/iam/)에서 인증되지 않은 사용자에 대해 Amazon Cognito가 생성한 IAM 역할을 찾습니다. 다음 정책을 추가하여 읽기 및 쓰기 권한을 Amazon S3 버킷에 부여합니다. IAM 역할 생성에 관한 자세한 내용은 *IAM 사용 설명서*의 [AWS 서비스에 대한 권한을 위임할 역할 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) 섹션을 참조하세요.

  인증되지 않은 사용자에 대해 Amazon Cognito가 생성한 IAM 역할에 이 역할 정책을 사용합니다.
**주의**  
인증되지 않은 사용자의 액세스를 활성화하면 버킷과 해당 버킷의 모든 객체, 전 세계 모든 사람에게 쓰기 권한을 부여하게 됩니다. 이러한 보안 태세는 이 사례의 기본 목표에 초점을 맞추는 데 유용합니다. 그러나 실제 사례의 경우, 인증된 사용자 및 객체 소유권의 사용 같이 더욱 강화된 보안을 사용하는 것이 좋습니다.

------
#### [ JSON ]

****  

  ```
  {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
        {
           "Effect": "Allow",
           "Action": [
              "s3:DeleteObject",
              "s3:GetObject",
              "s3:ListBucket",
              "s3:PutObject",
              "s3:PutObjectAcl"
           ],
           "Resource": [            
              "arn:aws:s3:::BUCKET_NAME",
              "arn:aws:s3:::BUCKET_NAME/*"
           ]
        }
     ]
  }
  ```

------

## CORS 구성
<a name="s3-example-photo-album-cors-configuration"></a>

브라우저 스크립트가 Amazon S3 버킷에 액세스하려면 먼저 다음과 같이 [CORS 구성](cors.md#configuring-cors-s3-bucket)을 설정해야 합니다.

**중요**  
새 S3 콘솔에서 CORS 구성은 JSON이어야 합니다.

------
#### [ JSON ]

```
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "HEAD",
            "GET",
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "ETag"
        ]
    }
]
```

------
#### [ XML ]

```
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
        <ExposeHeader>ETag</ExposeHeader>
    </CORSRule>
</CORSConfiguration>
```

------

## 웹 페이지
<a name="s3-example-photo-album-html"></a>

사진 업로드 애플리케이션을 위한 HTML은 브라우저 스크립트가 업로드 사용자 인터페이스를 생성하는 <div> 요소로 구성됩니다. 첫 번째 <script> 요소는 SDK를 브라우저 스크립트에 추가합니다. 두 번째 <script> 요소는 브라우저 스크립트 코드를 담는 외부 JavaScript 파일을 추가합니다.

```
<!DOCTYPE html>
<html>
  <head>
     <!-- **DO THIS**: -->
    <!--   Replace SDK_VERSION_NUMBER with the current SDK version number -->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.js"></script>
    <script src="./s3_photoExample.js"></script>
    <script>
       function getHtml(template) {
          return template.join('\n');
       }
       listAlbums();
    </script>
  </head>
  <body>
    <h1>My Photo Albums App</h1>
    <div id="app"></div>
  </body>
</html>
```

## SDK 구성
<a name="s3-example-photo-album-configure-sdk"></a>

Amazon Cognito 자격 증명 풀 ID를 제공하는 `CognitoIdentityCredentials` 메서드를 직접 호출하여 SDK를 구성하는 데 필요한 자격 증명을 획득합니다. 다음에는, `AWS.S3` 서비스 객체를 생성합니다.

```
var albumBucketName = "BUCKET_NAME";
var bucketRegion = "REGION";
var IdentityPoolId = "IDENTITY_POOL_ID";

AWS.config.update({
  region: bucketRegion,
  credentials: new AWS.CognitoIdentityCredentials({
    IdentityPoolId: IdentityPoolId,
  }),
});

var s3 = new AWS.S3({
  apiVersion: "2006-03-01",
  params: { Bucket: albumBucketName },
});
```

이 예제의 나머지 거의 모든 코드는 버킷의 앨범에 대한 정보를 수집 및 제공하고, 앨범에 사진을 업로드하고 업로드된 사진을 표시하며, 사진과 앨범을 삭제하는 일련의 함수로 구성됩니다. 이러한 함수는 다음과 같습니다.
+ `listAlbums`
+ `createAlbum`
+ `viewAlbum`
+ `addPhoto`
+ `deleteAlbum`
+ `deletePhoto`

## 버킷에 있는 앨범 목록 표시
<a name="s3-example-photo-album-list-albums"></a>

이 애플리케이션은 Amazon S3 버킷의 앨범을 객체로 생성합니다. 이 객체의 키는 객체 함수가 폴더임을 표시하는 슬래시 문자로 시작합니다. 버킷에 있는 모든 앨범의 목록을 표시하기 위해 애플리케이션의 `listAlbums` 함수는 `listObjects`를 사용하면서 `AWS.S3` 서비스 객체의 `commonPrefix` 메서드를 호출합니다. 따라서 이 호출은 앨범으로 사용되는 객체만 반환합니다.

이 함수의 나머지 부분은 Amazon S3 버킷에서 앨범 목록을 가져오고 웹 페이지에 앨범 목록을 표시하는 데 필요한 HTML을 생성합니다. 또한 개별 앨범 삭제 및 열기도 활성화합니다.

```
function listAlbums() {
  s3.listObjects({ Delimiter: "/" }, function (err, data) {
    if (err) {
      return alert("There was an error listing your albums: " + err.message);
    } else {
      var albums = data.CommonPrefixes.map(function (commonPrefix) {
        var prefix = commonPrefix.Prefix;
        var albumName = decodeURIComponent(prefix.replace("/", ""));
        return getHtml([
          "<li>",
          "<span onclick=\"deleteAlbum('" + albumName + "')\">X</span>",
          "<span onclick=\"viewAlbum('" + albumName + "')\">",
          albumName,
          "</span>",
          "</li>",
        ]);
      });
      var message = albums.length
        ? getHtml([
            "<p>Click on an album name to view it.</p>",
            "<p>Click on the X to delete the album.</p>",
          ])
        : "<p>You do not have any albums. Please Create album.";
      var htmlTemplate = [
        "<h2>Albums</h2>",
        message,
        "<ul>",
        getHtml(albums),
        "</ul>",
        "<button onclick=\"createAlbum(prompt('Enter Album Name:'))\">",
        "Create New Album",
        "</button>",
      ];
      document.getElementById("app").innerHTML = getHtml(htmlTemplate);
    }
  });
}
```

## 버킷에서 앨범 생성
<a name="s3-example-photo-album-create-album"></a>

Amazon S3 버킷에서 앨범을 생성하기 위해 애플리케이션의 `createAlbum` 함수는 새 앨범에 지정된 이름을 확인하여 적합한 문자가 이름에 포함되는지 확인합니다. 그런 다음 함수는 Amazon S3 객체 키를 구성하여 Amazon S3 서비스 객체의 `headObject` 메서드에 전달합니다. 이 메서드는 지정된 키에 대한 메타데이터를 반환하므로, 데이터를 반환하는 경우 해당 키가 있는 객체가 이미 있는 것입니다.

앨범이 아직 없는 경우 이 함수는 `putObject` 서비스 객체의 `AWS.S3`메서드를 호출하여 앨범을 생성합니다. 그런 다음 `viewAlbum` 함수를 호출하여 비어 있는 새 앨범을 표시합니다.

```
function createAlbum(albumName) {
  albumName = albumName.trim();
  if (!albumName) {
    return alert("Album names must contain at least one non-space character.");
  }
  if (albumName.indexOf("/") !== -1) {
    return alert("Album names cannot contain slashes.");
  }
  var albumKey = encodeURIComponent(albumName);
  s3.headObject({ Key: albumKey }, function (err, data) {
    if (!err) {
      return alert("Album already exists.");
    }
    if (err.code !== "NotFound") {
      return alert("There was an error creating your album: " + err.message);
    }
    s3.putObject({ Key: albumKey }, function (err, data) {
      if (err) {
        return alert("There was an error creating your album: " + err.message);
      }
      alert("Successfully created album.");
      viewAlbum(albumName);
    });
  });
}
```

## 앨범 보기
<a name="s3-example-photo-album-viewing-album"></a>

Amazon S3 버킷에 앨범의 콘텐츠를 표시하기 위해 애플리케이션의 `viewAlbum` 함수는 앨범 이름을 가져오고 해당 앨범에 대한 Amazon S3 키를 생성합니다. 그런 다음 이 함수는 `listObjects` 서비스 객체의 `AWS.S3` 메서드를 호출하여 앨범에 있는 모든 객체(사진)의 목록을 획득합니다.

이 함수의 나머지 부분은 앨범에서 객체(사진) 목록을 가져오고 웹 페이지에 사진을 표시하는 데 필요한 HTML을 생성합니다. 또한 개별 사진을 삭제하고 앨범 목록으로 다시 이동하는 작업도 활성화합니다.

```
function viewAlbum(albumName) {
  var albumPhotosKey = encodeURIComponent(albumName) + "/";
  s3.listObjects({ Prefix: albumPhotosKey }, function (err, data) {
    if (err) {
      return alert("There was an error viewing your album: " + err.message);
    }
    // 'this' references the AWS.Response instance that represents the response
    var href = this.request.httpRequest.endpoint.href;
    var bucketUrl = href + albumBucketName + "/";

    var photos = data.Contents.map(function (photo) {
      var photoKey = photo.Key;
      var photoUrl = bucketUrl + encodeURIComponent(photoKey);
      return getHtml([
        "<span>",
        "<div>",
        '<img style="width:128px;height:128px;" src="' + photoUrl + '"/>',
        "</div>",
        "<div>",
        "<span onclick=\"deletePhoto('" +
          albumName +
          "','" +
          photoKey +
          "')\">",
        "X",
        "</span>",
        "<span>",
        photoKey.replace(albumPhotosKey, ""),
        "</span>",
        "</div>",
        "</span>",
      ]);
    });
    var message = photos.length
      ? "<p>Click on the X to delete the photo</p>"
      : "<p>You do not have any photos in this album. Please add photos.</p>";
    var htmlTemplate = [
      "<h2>",
      "Album: " + albumName,
      "</h2>",
      message,
      "<div>",
      getHtml(photos),
      "</div>",
      '<input id="photoupload" type="file" accept="image/*">',
      '<button id="addphoto" onclick="addPhoto(\'' + albumName + "')\">",
      "Add Photo",
      "</button>",
      '<button onclick="listAlbums()">',
      "Back To Albums",
      "</button>",
    ];
    document.getElementById("app").innerHTML = getHtml(htmlTemplate);
  });
}
```

## 앨범에 사진 추가
<a name="s3-example-photo-album-adding-photos"></a>

애플리케이션의 `addPhoto` 함수가 Amazon S3 버킷의 앨범에 사진을 업로드하기 위해 웹 페이지에서 파일 선택기 요소를 사용하여 업로드할 파일을 식별합니다. 그런 현재 앨범 이름과 파일 이름에서 업로드할 사진에 대한 키를 구성합니다.

이 함수는 Amazon S3 서비스 객체의 `upload` 메서드를 호출하여 사진을 업로드합니다. 사진을 업로드한 후 이 함수는 업로드된 사진이 나타나도록 앨범을 다시 표시합니다.

```
function addPhoto(albumName) {
  var files = document.getElementById("photoupload").files;
  if (!files.length) {
    return alert("Please choose a file to upload first.");
  }
  var file = files[0];
  var fileName = file.name;
  var albumPhotosKey = encodeURIComponent(albumName) + "/";

  var photoKey = albumPhotosKey + fileName;

  // Use S3 ManagedUpload class as it supports multipart uploads
  var upload = new AWS.S3.ManagedUpload({
    params: {
      Bucket: albumBucketName,
      Key: photoKey,
      Body: file,
    },
  });

  var promise = upload.promise();

  promise.then(
    function (data) {
      alert("Successfully uploaded photo.");
      viewAlbum(albumName);
    },
    function (err) {
      return alert("There was an error uploading your photo: ", err.message);
    }
  );
}
```

## 사진 삭제
<a name="s3-example-photo-album-delete-photo"></a>

애플리케이션의 `deletePhoto` 함수가 Amazon S3 버킷의 앨범에서 사진을 삭제하기 위해 Amazon S3 서비스 객체의 `deleteObject` 메서드를 호출합니다. 이렇게 하면 함수에 전달된 `photoKey` 값으로 지정되는 사진이 삭제됩니다.

```
function deletePhoto(albumName, photoKey) {
  s3.deleteObject({ Key: photoKey }, function (err, data) {
    if (err) {
      return alert("There was an error deleting your photo: ", err.message);
    }
    alert("Successfully deleted photo.");
    viewAlbum(albumName);
  });
}
```

## 앨범 삭제
<a name="s3-example-photo-album-delete-album"></a>

애플리케이션의 `deleteAlbum` 함수가 Amazon S3 버킷의 앨범을 삭제하기 위해 Amazon S3 서비스 객체의 `deleteObjects` 메서드를 호출합니다.

```
function deleteAlbum(albumName) {
  var albumKey = encodeURIComponent(albumName) + "/";
  s3.listObjects({ Prefix: albumKey }, function (err, data) {
    if (err) {
      return alert("There was an error deleting your album: ", err.message);
    }
    var objects = data.Contents.map(function (object) {
      return { Key: object.Key };
    });
    s3.deleteObjects(
      {
        Delete: { Objects: objects, Quiet: true },
      },
      function (err, data) {
        if (err) {
          return alert("There was an error deleting your album: ", err.message);
        }
        alert("Successfully deleted album.");
        listAlbums();
      }
    );
  });
}
```

# Amazon S3에 사진 업로드: 전체 코드
<a name="s3-example-photo-album-full"></a>

이 섹션에는 사진이 Amazon S3 사진 앨범에 업로드되는 예제에 관한 전체 HTML 및 JavaScript 코드가 포함되어 있습니다. 자세한 내용과 사전 조건은 [상위 섹션](s3-example-photo-album.md)을 참조하세요.

HTML 예제:

```
<!DOCTYPE html>
<html>
  <head>
     <!-- **DO THIS**: -->
    <!--   Replace SDK_VERSION_NUMBER with the current SDK version number -->
    <script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.js"></script>
    <script src="./s3_photoExample.js"></script>
    <script>
       function getHtml(template) {
          return template.join('\n');
       }
       listAlbums();
    </script>
  </head>
  <body>
    <h1>My Photo Albums App</h1>
    <div id="app"></div>
  </body>
</html>
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_photoExample.html)에서 찾을 수 있습니다.

브라우저 스크립트 코드 예제:

```
var albumBucketName = "BUCKET_NAME";
var bucketRegion = "REGION";
var IdentityPoolId = "IDENTITY_POOL_ID";

AWS.config.update({
  region: bucketRegion,
  credentials: new AWS.CognitoIdentityCredentials({
    IdentityPoolId: IdentityPoolId,
  }),
});

var s3 = new AWS.S3({
  apiVersion: "2006-03-01",
  params: { Bucket: albumBucketName },
});

function listAlbums() {
  s3.listObjects({ Delimiter: "/" }, function (err, data) {
    if (err) {
      return alert("There was an error listing your albums: " + err.message);
    } else {
      var albums = data.CommonPrefixes.map(function (commonPrefix) {
        var prefix = commonPrefix.Prefix;
        var albumName = decodeURIComponent(prefix.replace("/", ""));
        return getHtml([
          "<li>",
          "<span onclick=\"deleteAlbum('" + albumName + "')\">X</span>",
          "<span onclick=\"viewAlbum('" + albumName + "')\">",
          albumName,
          "</span>",
          "</li>",
        ]);
      });
      var message = albums.length
        ? getHtml([
            "<p>Click on an album name to view it.</p>",
            "<p>Click on the X to delete the album.</p>",
          ])
        : "<p>You do not have any albums. Please Create album.";
      var htmlTemplate = [
        "<h2>Albums</h2>",
        message,
        "<ul>",
        getHtml(albums),
        "</ul>",
        "<button onclick=\"createAlbum(prompt('Enter Album Name:'))\">",
        "Create New Album",
        "</button>",
      ];
      document.getElementById("app").innerHTML = getHtml(htmlTemplate);
    }
  });
}

function createAlbum(albumName) {
  albumName = albumName.trim();
  if (!albumName) {
    return alert("Album names must contain at least one non-space character.");
  }
  if (albumName.indexOf("/") !== -1) {
    return alert("Album names cannot contain slashes.");
  }
  var albumKey = encodeURIComponent(albumName);
  s3.headObject({ Key: albumKey }, function (err, data) {
    if (!err) {
      return alert("Album already exists.");
    }
    if (err.code !== "NotFound") {
      return alert("There was an error creating your album: " + err.message);
    }
    s3.putObject({ Key: albumKey }, function (err, data) {
      if (err) {
        return alert("There was an error creating your album: " + err.message);
      }
      alert("Successfully created album.");
      viewAlbum(albumName);
    });
  });
}

function viewAlbum(albumName) {
  var albumPhotosKey = encodeURIComponent(albumName) + "/";
  s3.listObjects({ Prefix: albumPhotosKey }, function (err, data) {
    if (err) {
      return alert("There was an error viewing your album: " + err.message);
    }
    // 'this' references the AWS.Response instance that represents the response
    var href = this.request.httpRequest.endpoint.href;
    var bucketUrl = href + albumBucketName + "/";

    var photos = data.Contents.map(function (photo) {
      var photoKey = photo.Key;
      var photoUrl = bucketUrl + encodeURIComponent(photoKey);
      return getHtml([
        "<span>",
        "<div>",
        '<img style="width:128px;height:128px;" src="' + photoUrl + '"/>',
        "</div>",
        "<div>",
        "<span onclick=\"deletePhoto('" +
          albumName +
          "','" +
          photoKey +
          "')\">",
        "X",
        "</span>",
        "<span>",
        photoKey.replace(albumPhotosKey, ""),
        "</span>",
        "</div>",
        "</span>",
      ]);
    });
    var message = photos.length
      ? "<p>Click on the X to delete the photo</p>"
      : "<p>You do not have any photos in this album. Please add photos.</p>";
    var htmlTemplate = [
      "<h2>",
      "Album: " + albumName,
      "</h2>",
      message,
      "<div>",
      getHtml(photos),
      "</div>",
      '<input id="photoupload" type="file" accept="image/*">',
      '<button id="addphoto" onclick="addPhoto(\'' + albumName + "')\">",
      "Add Photo",
      "</button>",
      '<button onclick="listAlbums()">',
      "Back To Albums",
      "</button>",
    ];
    document.getElementById("app").innerHTML = getHtml(htmlTemplate);
  });
}

function addPhoto(albumName) {
  var files = document.getElementById("photoupload").files;
  if (!files.length) {
    return alert("Please choose a file to upload first.");
  }
  var file = files[0];
  var fileName = file.name;
  var albumPhotosKey = encodeURIComponent(albumName) + "/";

  var photoKey = albumPhotosKey + fileName;

  // Use S3 ManagedUpload class as it supports multipart uploads
  var upload = new AWS.S3.ManagedUpload({
    params: {
      Bucket: albumBucketName,
      Key: photoKey,
      Body: file,
    },
  });

  var promise = upload.promise();

  promise.then(
    function (data) {
      alert("Successfully uploaded photo.");
      viewAlbum(albumName);
    },
    function (err) {
      return alert("There was an error uploading your photo: ", err.message);
    }
  );
}

function deletePhoto(albumName, photoKey) {
  s3.deleteObject({ Key: photoKey }, function (err, data) {
    if (err) {
      return alert("There was an error deleting your photo: ", err.message);
    }
    alert("Successfully deleted photo.");
    viewAlbum(albumName);
  });
}

function deleteAlbum(albumName) {
  var albumKey = encodeURIComponent(albumName) + "/";
  s3.listObjects({ Prefix: albumKey }, function (err, data) {
    if (err) {
      return alert("There was an error deleting your album: ", err.message);
    }
    var objects = data.Contents.map(function (object) {
      return { Key: object.Key };
    });
    s3.deleteObjects(
      {
        Delete: { Objects: objects, Quiet: true },
      },
      function (err, data) {
        if (err) {
          return alert("There was an error deleting your album: ", err.message);
        }
        alert("Successfully deleted album.");
        listAlbums();
      }
    );
  });
}
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_photoExample.js)에서 찾을 수 있습니다.

# Amazon S3 Node.js 예제
<a name="s3-node-examples"></a>

다음 주제는 브라우저에서 Node.js를 사용하는 Amazon S3 버킷과의 상호 작용을 위해 AWS SDK for JavaScript가 사용되는 방식의 예제 두 가지를 설명합니다.

**Topics**
+ [Amazon S3 버킷 생성 및 사용](s3-example-creating-buckets.md)
+ [Amazon S3 버킷 구성](s3-example-configuring-buckets.md)
+ [Amazon S3 버킷 액세스 권한 관리](s3-example-access-permissions.md)
+ [Amazon S3 버킷 정책 작업](s3-example-bucket-policies.md)
+ [Amazon S3 버킷을 정적 웹 호스트로 사용](s3-example-static-web-host.md)

# Amazon S3 버킷 생성 및 사용
<a name="s3-example-creating-buckets"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 계정에서 Amazon S3 버킷 목록을 가져오고 표시하는 방법
+ Amazon S3 버킷을 생성하는 방법
+ 지정된 버킷에 객체를 업로드하는 방법.

## 시나리오
<a name="s3-example-creating-buckets-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 기존 Amazon S3 버킷 목록을 가져오고 버킷을 생성하며 지정된 버킷에 파일을 업로드합니다. Node.js 모듈은 다음 Amazon S3 클라이언트 클래스 메서드를 사용하여 Amazon S3 버킷에서 정보를 가져오고 파일을 업로드하기 위해 SDK for JavaScript를 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listBuckets-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listBuckets-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#createBucket-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#createBucket-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjects-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucket-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucket-property)

## 사전 필수 작업
<a name="s3-example-creating-buckets-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SDK 구성
<a name="s3-example-creating-buckets-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## Amazon S3 버킷 목록 표시
<a name="s3-example-creating-buckets-list-buckets"></a>

파일 이름이 `s3_listbuckets.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon Simple Storage Service에 액세스하려면 `AWS.S3` 서비스 객체를 생성합니다. Amazon S3 서비스 객체의 `listBuckets` 메서드를 직접 호출하여 버킷의 목록을 검색합니다. 콜백 함수의 `data` 파라미터에는 버킷을 표시하기 위한 맵 배열을 포함하는 `Buckets` 속성이 있습니다. 콘솔에 로그인하여 버킷 목록을 표시합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Call S3 to list the buckets
s3.listBuckets(function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Buckets);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_listbuckets.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_listbuckets.js)에서 찾을 수 있습니다.

## Amazon S3 버킷 생성
<a name="s3-example-creating-buckets-new-bucket"></a>

파일 이름이 `s3_createbucket.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. `AWS.S3` 서비스 객체를 생성합니다. 이 모듈은 단일 명령줄 인수를 가져와서 새 버킷의 이름을 지정합니다.

새로 생성된 버킷의 이름을 포함하여 Amazon S3 서비스 객체의 `createBucket` 메서드를 직접 호출하는 데 사용되는 파라미터를 담을 변수를 추가합니다. Amazon S3가 버킷을 성공적으로 생성한 후 콜백 함수가 새 버킷의 위치를 콘솔에 로깅합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Create the parameters for calling createBucket
var bucketParams = {
  Bucket: process.argv[2],
};

// call S3 to create the bucket
s3.createBucket(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Location);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_createbucket.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_createbucket.js)에서 찾을 수 있습니다.

## Amazon S3 버킷에 파일 업로드
<a name="s3-example-creating-buckets-upload-file"></a>

파일 이름이 `s3_upload.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. `AWS.S3` 서비스 객체를 생성합니다. 이 모듈은 두 개의 명령줄 인수를 가져옵니다. 첫 번째 인수는 대상 버킷을 지정하고 두 번째 인수는 업로드할 파일을 지정합니다.

Amazon S3 서비스 객체의 `upload` 메서드를 직접 호출하는 데 필요한 파라미터가 있는 변수를 생성합니다. 대상 버킷의 이름을 `Bucket` 파라미터에 제공합니다. `Key` 파라미터는 선택한 파일의 이름으로 설정되며, 이 이름은 Node.js `path` 모듈을 사용하여 가져올 수 있습니다. `Body` 파라미터는 파일의 콘텐츠로 설정되며, 이 콘텐츠는 Node.js `createReadStream` 모듈의 `fs`을 사용하여 가져올 수 있습니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
var s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// call S3 to retrieve upload file to specified bucket
var uploadParams = { Bucket: process.argv[2], Key: "", Body: "" };
var file = process.argv[3];

// Configure the file stream and obtain the upload parameters
var fs = require("fs");
var fileStream = fs.createReadStream(file);
fileStream.on("error", function (err) {
  console.log("File Error", err);
});
uploadParams.Body = fileStream;
var path = require("path");
uploadParams.Key = path.basename(file);

// call S3 to retrieve upload file to specified bucket
s3.upload(uploadParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  }
  if (data) {
    console.log("Upload Success", data.Location);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_upload.js BUCKET_NAME FILE_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_upload.js)에서 찾을 수 있습니다.

## Amazon S3 버킷의 객체 나열
<a name="s3-example-listing-objects"></a>

파일 이름이 `s3_listobjects.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. `AWS.S3` 서비스 객체를 생성합니다.

읽을 버킷의 이름을 포함하여 Amazon S3 서비스 객체의 `listObjects` 메서드를 호출하는 데 사용되는 파라미터를 담을 변수를 추가합니다. 콜백 함수는 객체(파일)의 목록 또는 실패 메시지를 로깅합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Create the parameters for calling listObjects
var bucketParams = {
  Bucket: "BUCKET_NAME",
};

// Call S3 to obtain a list of the objects in the bucket
s3.listObjects(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_listobjects.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_listobjects.js)에서 찾을 수 있습니다.

## Amazon S3 버킷 삭제
<a name="s3-example-deleting-buckets"></a>

파일 이름이 `s3_deletebucket.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. `AWS.S3` 서비스 객체를 생성합니다.

삭제할 버킷의 이름을 포함하여 Amazon S3 서비스 객체의 `createBucket` 메서드를 호출하는 데 사용되는 파라미터를 담을 변수를 추가합니다. 버킷을 삭제하려면 버킷이 비어 있어야 합니다. 콜백 함수는 성공 또는 실패 메시지를 로깅합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Create params for S3.deleteBucket
var bucketParams = {
  Bucket: "BUCKET_NAME",
};

// Call S3 to delete the bucket
s3.deleteBucket(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_deletebucket.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_deletebucket.js)에서 찾을 수 있습니다.

# Amazon S3 버킷 구성
<a name="s3-example-configuring-buckets"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 버킷에 대한 CORS(교차 오리진 리소스 공유) 권한을 구성하는 방법.

## 시나리오
<a name="s3-example-configuring-buckets-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 Amazon S3 버킷 목록을 표시하고 CORS 및 버킷 로깅을 구성합니다. Node.js 모듈은 SDK for JavaScript로 Amazon S3 클라이언트 클래스의 다음 메서드를 사용하여 선택한 Amazon S3 버킷을 구성합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketCors-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketCors-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketCors-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketCors-property)

Amazon S3 버킷을 사용하는 CORS 구성 사용에 대한 자세한 내용은 *Amazon Simple Storage Service 사용 설명서*의 [CORS(Cross-Origin Resource Sharing)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html)를 참조하세요.

## 사전 필수 작업
<a name="s3-example-configuring-buckets-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SDK 구성
<a name="s3-example-configuring-buckets-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 버킷 CORS 구성 검색
<a name="s3-example-configuring-buckets-get-cors"></a>

파일 이름이 `s3_getcors.js`인 Node.js 모듈을 생성합니다. 이 모듈은 단일 명령줄 인수를 가져와서 원하는 CORS 구성이 있는 버킷을 지정합니다. 위와 같이 SDK를 구성해야 합니다. `AWS.S3` 서비스 객체를 생성합니다.

전달해야 하는 유일한 파라미터는 `getBucketCors` 메서드를 호출할 때 선택한 버킷의 이름입니다. 현재 버킷에 CORS 구성이 있는 경우 해당 구성은 Amazon S3에서 콜백 함수에 전달되는 `data` 파라미터의 `CORSRules` 속성으로 반환됩니다.

선택한 버킷에 CORS 구성이 없는 경우 해당 정보는 `error` 파라미터에서 콜백 함수에 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Set the parameters for S3.getBucketCors
var bucketParams = { Bucket: process.argv[2] };

// call S3 to retrieve CORS configuration for selected bucket
s3.getBucketCors(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", JSON.stringify(data.CORSRules));
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_getcors.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_getcors.js)에서 찾을 수 있습니다.

## 버킷 CORS 구성 설정
<a name="s3-example-configuring-buckets-put-cors"></a>

파일 이름이 `s3_setcors.js`인 Node.js 모듈을 생성합니다. 이 모듈은 여러 명령줄 인수를 가져옵니다. 이러한 인수 중 첫 번째는 설정할 CORS 구성이 있는 버킷을 지정합니다. 추가 인수는 버킷에 허용할 HTTP 메서드(POST, GET, PUT, PATCH, DELETE, POST)를 열거합니다. 위와 같이 SDK를 구성합니다.

 `AWS.S3` 서비스 객체를 생성합니다. 다음에는 `putBucketCors` 서비스 객체의 `AWS.S3` 메서드에 필요한 CORS 구성의 값을 담을 JSON 객체를 생성합니다. `"Authorization"` 값에 `AllowedHeaders`을 지정하고 `"*"` 값에 `AllowedOrigins`를 지정합니다. 처음에는 비어 있는 배열로 `AllowedMethods`의 값을 설정합니다.

허용된 메서드를 명령줄 파라미터로 Node.js 모듈에 지정하여 파라미터 중 하나와 일치하는 각 메서드를 추가합니다. 결과적으로 생성된 CORS 구성을 `CORSRules` 파라미터에 포함된 구성 배열에 추가합니다. `Bucket` 파라미터에서 CORS에 구성할 버킷을 지정합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Create initial parameters JSON for putBucketCors
var thisConfig = {
  AllowedHeaders: ["Authorization"],
  AllowedMethods: [],
  AllowedOrigins: ["*"],
  ExposeHeaders: [],
  MaxAgeSeconds: 3000,
};

// Assemble the list of allowed methods based on command line parameters
var allowedMethods = [];
process.argv.forEach(function (val, index, array) {
  if (val.toUpperCase() === "POST") {
    allowedMethods.push("POST");
  }
  if (val.toUpperCase() === "GET") {
    allowedMethods.push("GET");
  }
  if (val.toUpperCase() === "PUT") {
    allowedMethods.push("PUT");
  }
  if (val.toUpperCase() === "PATCH") {
    allowedMethods.push("PATCH");
  }
  if (val.toUpperCase() === "DELETE") {
    allowedMethods.push("DELETE");
  }
  if (val.toUpperCase() === "HEAD") {
    allowedMethods.push("HEAD");
  }
});

// Copy the array of allowed methods into the config object
thisConfig.AllowedMethods = allowedMethods;
// Create array of configs then add the config object to it
var corsRules = new Array(thisConfig);

// Create CORS params
var corsParams = {
  Bucket: process.argv[2],
  CORSConfiguration: { CORSRules: corsRules },
};

// set the new CORS configuration on the selected bucket
s3.putBucketCors(corsParams, function (err, data) {
  if (err) {
    // display error message
    console.log("Error", err);
  } else {
    // update the displayed CORS config for the selected bucket
    console.log("Success", data);
  }
});
```

예제를 실행하려면 다음과 같이 하나 이상의 HTTP 메서드를 포함하여 명령줄에 다음을 입력합니다.

```
node s3_setcors.js BUCKET_NAME get put
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_setcors.js)에서 찾을 수 있습니다.

# Amazon S3 버킷 액세스 권한 관리
<a name="s3-example-access-permissions"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon S3 버킷에 대한 액세스 제어 목록을 가져오거나 설정하는 방법.

## 시나리오
<a name="w2aac20c25c27c13b9"></a>

이 예제에서는 Node.js 모듈을 사용하여 선택한 버킷에 대한 버킷 ACL(액세스 제어 목록)을 표시하고 선택한 버킷에 대한 ACL에 변경 사항을 적용합니다. Node.js 모듈은 SDK for JavaScript로 Amazon S3 클라이언트 클래스의 다음 메서드를 사용하여 Amazon S3 버킷 액서스 권한을 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketAcl-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketAcl-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketAcl-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketAcl-property)

Amazon S3 버킷 액세스 제어 목록(ACL)에 대한 자세한 내용은 *Amazon Simple Storage Service 사용 안내서*의 [ACL을 사용한 액세스 관리](https://docs.aws.amazon.com/AmazonS3/latest/userguide/S3_ACLs_UsingACLs.html)를 참조하세요.

## 사전 필수 작업
<a name="w2aac20c25c27c13c11"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SDK 구성
<a name="s3-example-access-permissions-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 현재 버킷 액세스 제어 목록 검색
<a name="s3-example-access-permissions-get-acl"></a>

파일 이름이 `s3_getbucketacl.js`인 Node.js 모듈을 생성합니다. 이 모듈은 단일 명령줄 인수를 가져와서 원하는 ACL 구성이 있는 버킷을 지정합니다. 위와 같이 SDK를 구성해야 합니다.

`AWS.S3` 서비스 객체를 생성합니다. 전달해야 하는 유일한 파라미터는 `getBucketAcl` 메서드를 호출할 때 선택한 버킷의 이름입니다. 현재 액세스 제어 목록(ACL) 구성은 Amazon S3가 콜백 함수에 전달하는 `data` 파라미터에서 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var bucketParams = { Bucket: process.argv[2] };
// call S3 to retrieve policy for selected bucket
s3.getBucketAcl(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", data.Grants);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_getbucketacl.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_getbucketacl.js)에서 찾을 수 있습니다.

# Amazon S3 버킷 정책 작업
<a name="s3-example-bucket-policies"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon S3 버킷의 버킷 정책을 검색하는 방법
+ Amazon S3 버킷의 버킷 정책을 추가하거나 업데이트하는 방법
+ Amazon S3 버킷의 버킷 정책을 삭제하는 방법

## 시나리오
<a name="w2aac20c25c27c15b9"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 Amazon S3 버킷에 대한 버킷 정책을 검색, 설정 또는 삭제합니다. Node.js 모듈은 SDK for JavaScript로 Amazon S3 클라이언트 클래스의 다음 메서드를 사용하여 선택한 Amazon S3 버킷에 대한 정책을 구성합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketPolicy-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketPolicy-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucketPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucketPolicy-property)

Amazon S3의 버킷 정책에 대한 자세한 내용은 *Amazon Simple Storage Service 사용 설명서*의 [버킷 정책 및 사용자 정책 사용](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-iam-policies.html)을 참조하세요.

## 사전 필수 작업
<a name="w2aac20c25c27c15c11"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SDK 구성
<a name="s3-example-bucket-policies-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 현재 버킷 정책 검색
<a name="s3-example-bucket-policies-get-policy"></a>

파일 이름이 `s3_getbucketpolicy.js`인 Node.js 모듈을 생성합니다. 이 모듈은 원하는 정책이 있는 버킷을 지정하는 단일 명령줄 인수를 가져옵니다. 위와 같이 SDK를 구성해야 합니다.

`AWS.S3` 서비스 객체를 생성합니다. 전달해야 하는 유일한 파라미터는 `getBucketPolicy` 메서드를 호출할 때 선택한 버킷의 이름입니다. 현재 버킷에 정책이 있는 경우 해당 정책은 Amazon S3에서 콜백 함수에 전달되는 `data` 파라미터에 반환됩니다.

선택한 버킷에 정책이 없는 경우 해당 정보는 `error` 파라미터에서 콜백 함수에 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var bucketParams = { Bucket: process.argv[2] };
// call S3 to retrieve policy for selected bucket
s3.getBucketPolicy(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", data.Policy);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_getbucketpolicy.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_getbucketpolicy.js)에서 찾을 수 있습니다.

## 간단한 버킷 정책 설정
<a name="s3-example-bucket-policies-set-policy"></a>

파일 이름이 `s3_setbucketpolicy.js`인 Node.js 모듈을 생성합니다. 이 모듈은 적용할 정책이 있는 버킷을 지정하는 단일 명령줄 인수를 가져옵니다. 위와 같이 SDK를 구성합니다.

`AWS.S3` 서비스 객체를 생성합니다. 버킷 정책은 JSON 문서에서 지정됩니다. 먼저, 버킷을 식별하는 `Resource` 값을 제외하고 정책을 지정하기 위한 모든 값을 포함하는 JSON 객체를 생성합니다.

정책에 필요한 `Resource` 문자열의 형식을 지정하여 선택한 버킷의 이름을 통합합니다. 해당 문자열을 JSON 객체에 삽입합니다. 버킷의 이름과 문자열 값으로 변환된 JSON 정책을 포함하여 `putBucketPolicy` 메서드를 위한 파라미터를 준비합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var readOnlyAnonUserPolicy = {
  Version: "2012-10-17",
  Statement: [
    {
      Sid: "AddPerm",
      Effect: "Allow",
      Principal: "*",
      Action: ["s3:GetObject"],
      Resource: [""],
    },
  ],
};

// create selected bucket resource string for bucket policy
var bucketResource = "arn:aws:s3:::" + process.argv[2] + "/*";
readOnlyAnonUserPolicy.Statement[0].Resource[0] = bucketResource;

// convert policy JSON into string and assign into params
var bucketPolicyParams = {
  Bucket: process.argv[2],
  Policy: JSON.stringify(readOnlyAnonUserPolicy),
};

// set the new policy on the selected bucket
s3.putBucketPolicy(bucketPolicyParams, function (err, data) {
  if (err) {
    // display error message
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_setbucketpolicy.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_setbucketpolicy.js)에서 찾을 수 있습니다.

## 버킷 정책 삭제
<a name="s3-example-bucket-policies-delete-policy"></a>

파일 이름이 `s3_deletebucketpolicy.js`인 Node.js 모듈을 생성합니다. 이 모듈은 삭제할 정책이 있는 버킷을 지정하는 단일 명령줄 인수를 가져옵니다. 위와 같이 SDK를 구성합니다.

 `AWS.S3` 서비스 객체를 생성합니다. `deleteBucketPolicy` 메서드를 호출할 때 전달해야 하는 유일한 파라미터는 선택한 버킷의 이름입니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var bucketParams = { Bucket: process.argv[2] };
// call S3 to delete policy for selected bucket
s3.deleteBucketPolicy(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_deletebucketpolicy.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_deletebucketpolicy.js)에서 찾을 수 있습니다.

# Amazon S3 버킷을 정적 웹 호스트로 사용
<a name="s3-example-static-web-host"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon S3 버킷을 정적 웹 호스트로 설정하는 방법

## 시나리오
<a name="s3-example-static-web-host-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 정적 웹 호스트 역할을 하는 버킷 중 하나를 구성합니다. Node.js 모듈은 SDK for JavaScript로 Amazon S3 클라이언트 클래스의 다음 메서드를 사용하여 선택한 Amazon S3 버킷을 구성합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketWebsite-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketWebsite-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketWebsite-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketWebsite-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucketWebsite-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucketWebsite-property)

Amazon S3 버킷을 정적 웹 호스트로 사용하는 방법에 대한 자세한 내용은 *Amazon Simple Storage Service 사용 설명서*의 [Amazon S3에서 정적 웹 사이트 호스팅](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html)을 참조하세요.

## 사전 필수 작업
<a name="s3-example-static-web-host-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SDK 구성
<a name="s3-example-static-web-host-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 현재 버킷 웹 사이트 구성 검색
<a name="s3-example-static-web-host-get-website"></a>

파일 이름이 `s3_getbucketwebsite.js`인 Node.js 모듈을 생성합니다. 이 모듈은 원하는 웹 사이트 구성이 있는 버킷을 지정하는 단일 명령줄 인수를 가져옵니다. 위와 같이 SDK를 구성합니다.

`AWS.S3` 서비스 객체를 생성합니다. 버킷 목록에서 선택한 버킷에 대한 현재 버킷 웹 사이트 구성을 검색하는 함수를 생성합니다. 전달해야 하는 유일한 파라미터는 `getBucketWebsite` 메서드를 호출할 때 선택한 버킷의 이름입니다. 현재 버킷에 웹 사이트가 구성된 경우 해당 구성은 Amazon S3에서 콜백 함수에 전달되는 `data` 파라미터에 반환됩니다.

선택한 버킷에 웹 사이트 구성이 없는 경우 해당 정보는 `err` 파라미터에서 콜백 함수에 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var bucketParams = { Bucket: process.argv[2] };

// call S3 to retrieve the website configuration for selected bucket
s3.getBucketWebsite(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_getbucketwebsite.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_getbucketwebsite.js)에서 찾을 수 있습니다.

## 버킷 웹 사이트 구성 설정
<a name="s3-example-static-web-host-set-website"></a>

파일 이름이 `s3_setbucketwebsite.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. `AWS.S3` 서비스 객체를 생성합니다.

버킷 웹 사이트 구성을 적용하는 함수를 생성합니다. 선택한 버킷은 이 구성을 사용하여 정적 웹 호스트의 역할을 수행할 수 있습니다. 웹 사이트 구성은 JSON에서 지정됩니다. 먼저, 오류 문서를 식별하는 `Key` 값과 인덱스 문서를 식별하는 `Suffix` 값을 제외하고 웹 사이트 구성을 지정하기 위한 모든 값을 포함하는 JSON 객체를 생성합니다.

텍스트 입력 요소의 값을 JSON 객체에 삽입합니다. 버킷의 이름과 JSON 웹 사이트 구성을 포함하여 `putBucketWebsite` 메서드를 위한 파라미터를 준비합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

// Create JSON for putBucketWebsite parameters
var staticHostParams = {
  Bucket: "",
  WebsiteConfiguration: {
    ErrorDocument: {
      Key: "",
    },
    IndexDocument: {
      Suffix: "",
    },
  },
};

// Insert specified bucket name and index and error documents into params JSON
// from command line arguments
staticHostParams.Bucket = process.argv[2];
staticHostParams.WebsiteConfiguration.IndexDocument.Suffix = process.argv[3];
staticHostParams.WebsiteConfiguration.ErrorDocument.Key = process.argv[4];

// set the new website configuration on the selected bucket
s3.putBucketWebsite(staticHostParams, function (err, data) {
  if (err) {
    // display error message
    console.log("Error", err);
  } else {
    // update the displayed website configuration for the selected bucket
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_setbucketwebsite.js BUCKET_NAME INDEX_PAGE ERROR_PAGE
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_setbucketwebsite.js)에서 찾을 수 있습니다.

## 버킷 웹 사이트 구성 삭제
<a name="s3-example-static-web-host-delete-website"></a>

파일 이름이 `s3_deletebucketwebsite.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. `AWS.S3` 서비스 객체를 생성합니다.

선택한 버킷에 대한 웹 사이트 구성을 삭제하는 함수를 생성합니다. `deleteBucketWebsite` 메서드를 호출할 때 전달해야 하는 유일한 파라미터는 선택한 버킷의 이름입니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var bucketParams = { Bucket: process.argv[2] };

// call S3 to delete website configuration for selected bucket
s3.deleteBucketWebsite(bucketParams, function (error, data) {
  if (error) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node s3_deletebucketwebsite.js BUCKET_NAME
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_deletebucketwebsite.js)에서 찾을 수 있습니다.

# Amazon Simple Email Services 예제
<a name="ses-examples"></a>

Amazon Simple Email Service(Amazon SES)는 디지털 마케팅 담당자 및 애플리케이션 개발자가 마케팅, 알림 및 거래 이메일을 전송하는 데 도움이 되도록 설계된 클라우드 기반 이메일 전송 서비스입니다. 이 서비스는 이메일을 사용하여 고객과 연락하는 모든 규모의 기업을 위한 안정적이고 비용 효과적인 서비스입니다.

![\[JavaScript 환경, SDK, Amazon SES 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-ses.png)


Amazon SES용 JavaScript API는 `AWS.SES` 클라이언트 클래스를 통해 노출됩니다. Amazon SES 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html) 섹션을 참조하세요.

**Topics**
+ [Amazon SES 자격 증명 관리](ses-examples-managing-identities.md)
+ [Amazon SES에서 이메일 템플릿 작업](ses-examples-creating-template.md)
+ [Amazon SES로 이메일 전송](ses-examples-sending-email.md)
+ [Amazon SES에서 이메일 수신을 위한 IP 주소 필터 사용](ses-examples-ip-filters.md)
+ [Amazon SES에서 수신 규칙 사용](ses-examples-receipt-rules.md)

# Amazon SES 자격 증명 관리
<a name="ses-examples-managing-identities"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SES에 사용되는 이메일 주소 및 도메인을 확인하는 방법
+ IAM 정책을 Amazon SES 자격 증명에 할당하는 방법
+ AWS 계정의 모든 Amazon SES 자격 증명을 나열하는 방법
+ Amazon SES에 사용되는 자격 증명을 삭제하는 방법

Amazon SES *자격 증명*은 Amazon SES에서 이메일을 보내는 데 사용하는 이메일 주소 또는 도메인입니다. Amazon SES에서는 이메일 자격 증명을 확인해야 합니다. 이렇게 해당 자격 증명을 소유하고 있음을 확인하고 다른 사람이 이를 사용하지 못하게 방지합니다.

Amazon SES에서 이메일 주소 및 도메인을 확인하는 방법에 대한 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [이메일 주소 및 도메인 확인](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html) 섹션을 참조하세요. Amazon SES의 전송 권한 부여에 관한 자세한 내용은 [Amazon SES 전송 권한 부여의 개요](Amazon Simple Email Service Developer Guidesending-authorization-overview.html) 섹션을 참조하세요.

## 시나리오
<a name="ses-examples-verifying-identities-scenario"></a>

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SES 자격 증명을 확인하고 관리합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `AWS.SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 주소와 도메인을 확인합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#listIdentities-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#listIdentities-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteIdentity-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteIdentity-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#verifyEmailIdentity-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#verifyEmailIdentity-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#verifyDomainIdentity-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#verifyDomainIdentity-property)

## 사전 필수 작업
<a name="ses-examples-verifying-identities-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 JSON 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SDK 구성
<a name="ses-examples-verifying-identities-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');

// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 자격 증명 나열
<a name="ses-examples-listing-identities"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 주소와 도메인을 나열합니다. 파일 이름이 `ses_listidentities.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`AWS.SES` 클라이언트 클래스의 `listIdentities` 메서드에 대한 `IdentityType` 및 기타 파라미터를 전달할 객체를 생성합니다. `listIdentities` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SES 서비스 객체를 간접 호출하기 위한 promise를 생성합니다.

그런 다음 promise 콜백에서 `response`를 처리합니다. promise에서 반환된 `data`는 `IdentityType` 파라미터에 지정된 도메인 자격 증명의 배열을 포함하고 있습니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create listIdentities params
var params = {
  IdentityType: "Domain",
  MaxItems: 10,
};

// Create the promise and SES service object
var listIDsPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .listIdentities(params)
  .promise();

// Handle promise's fulfilled/rejected states
listIDsPromise
  .then(function (data) {
    console.log(data.Identities);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ses_listidentities.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_listidentities.js)에서 찾을 수 있습니다.

## 이메일 주소 자격 증명 확인
<a name="ses-examples-verifying-email"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 발신자를 확인합니다. 파일 이름이 `ses_verifyemailidentity.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. Amazon EC2에 액세스하려면 `AWS.SES` 서비스 객체를 생성합니다.

`AWS.SES` 클라이언트 클래스의 `verifyEmailIdentity` 메서드에 대한 `EmailAddress` 파라미터를 전달할 객체를 생성합니다. `verifyEmailIdentity` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SES service object
var verifyEmailPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .verifyEmailIdentity({ EmailAddress: "ADDRESS@DOMAIN.EXT" })
  .promise();

// Handle promise's fulfilled/rejected states
verifyEmailPromise
  .then(function (data) {
    console.log("Email verification initiated");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. 확인을 위해 Amazon SES에 도메인이 추가됩니다.

```
node ses_verifyemailidentity.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_verifyemailidentity.js)에서 찾을 수 있습니다.

## 도메인 자격 증명 확인
<a name="ses-examples-verifying-domains"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 도메인을 확인합니다. 파일 이름이 `ses_verifydomainidentity.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`AWS.SES` 클라이언트 클래스의 `verifyDomainIdentity` 메서드에 대한 `Domain` 파라미터를 전달할 객체를 생성합니다. `verifyDomainIdentity` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SES 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var verifyDomainPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .verifyDomainIdentity({ Domain: "DOMAIN_NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
verifyDomainPromise
  .then(function (data) {
    console.log("Verification Token: " + data.VerificationToken);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. 확인을 위해 Amazon SES에 도메인이 추가됩니다.

```
node ses_verifydomainidentity.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_verifydomainidentity.js)에서 찾을 수 있습니다.

## 자격 증명 삭제
<a name="ses-examples-deleting-identities"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용되는 이메일 주소 또는 도메인을 삭제합니다. 파일 이름이 `ses_deleteidentity.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`AWS.SES` 클라이언트 클래스의 `deleteIdentity` 메서드에 대한 `Identity` 파라미터를 전달할 객체를 생성합니다. `deleteIdentity` 메서드를 직접 호출하려면 Amazon SES 서비스 객체를 간접 호출하기 위한 `request`를 생성하여 파라미터를 전달합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var deletePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .deleteIdentity({ Identity: "DOMAIN_NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
deletePromise
  .then(function (data) {
    console.log("Identity Deleted");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node ses_deleteidentity.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_deleteidentity.js)에서 찾을 수 있습니다.

# Amazon SES에서 이메일 템플릿 작업
<a name="ses-examples-creating-template"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 모든 이메일 템플릿의 목록을 가져옵니다.
+ 이메일 템플릿을 검색하고 업데이트합니다.
+ 이메일 템플릿을 생성하고 삭제합니다.

Amazon SES에서 이메일 템플릿을 사용하여 맞춤형 이메일 메시지를 전송할 수 있습니다. Amazon Simple Email Service(Amazon SES)에서 이메일 템플릿을 생성하고 사용하는 방법에 대한 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [템플릿을 사용하여 Amazon SES API를 통해 맞춤형 이메일 전송](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html) 섹션을 참조하세요.

## 시나리오
<a name="ses-examples-creating-template-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 이메일 템플릿을 작업합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `AWS.SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 템플릿을 생성하고 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#listTemplates-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#listTemplates-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createTemplate-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createTemplate-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#getTemplate-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#getTemplate-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteTemplate-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteTemplate-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#updateTemplate-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#updateTemplate-property)

## 사전 필수 작업
<a name="ses-examples-creating-template-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 파일 생성에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 이메일 템플릿 나열
<a name="ses-examples-listing-templates"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다. 파일 이름이 `ses_listtemplates.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`AWS.SES` 클라이언트 클래스의 `listTemplates` 메서드에 대한 파라미터를 전달할 객체를 생성합니다. `listTemplates` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .listTemplates({ MaxItems: ITEMS_COUNT })
  .promise();

// Handle promise's fulfilled/rejected states
templatePromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 템플릿 목록을 반환합니다.

```
node ses_listtemplates.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_listtemplates.js)에서 찾을 수 있습니다.

## 이메일 템플릿 가져오기
<a name="ses-examples-get-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 가져옵니다. 파일 이름이 `ses_gettemplate.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`AWS.SES` 클라이언트 클래스의 `getTemplate` 메서드에 대한 `TemplateName` 파라미터를 전달할 객체를 생성합니다. `getTemplate` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk");
// Set the AWS Region.
AWS.config.update({ region: "REGION" });

// Create the promise and Amazon Simple Email Service (Amazon SES) service object.
var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .getTemplate({ TemplateName: "TEMPLATE_NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
templatePromise
  .then(function (data) {
    console.log(data.Template.SubjectPart);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 템플릿 세부 정보를 반환합니다.

```
node ses_gettemplate.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_gettemplate.js)에서 찾을 수 있습니다.

## 이메일 템플릿 생성
<a name="ses-examples-create-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다. 파일 이름이 `ses_createtemplate.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`TemplateName`, `HtmlPart`, `SubjectPart` 및 `TextPart`를 포함하여 `AWS.SES` 클라이언트 클래스의 `createTemplate` 메서드에 대한 파라미터를 전달할 객체를 생성합니다. `createTemplate` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create createTemplate params
var params = {
  Template: {
    TemplateName: "TEMPLATE_NAME" /* required */,
    HtmlPart: "HTML_CONTENT",
    SubjectPart: "SUBJECT_LINE",
    TextPart: "TEXT_CONTENT",
  },
};

// Create the promise and SES service object
var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .createTemplate(params)
  .promise();

// Handle promise's fulfilled/rejected states
templatePromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. 템플릿이 Amazon SES에 추가됩니다.

```
node ses_createtemplate.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_createtemplate.js)에서 찾을 수 있습니다.

## 이메일 템플릿 업데이트
<a name="ses-examples-update-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다. 파일 이름이 `ses_updatetemplate.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`AWS.SES` 클라이언트 클래스의 `updateTemplate` 메서드에 전달된 필수 `TemplateName` 파라미터와 함께 템플릿에서 업데이트하려는 `Template` 파라미터 값을 전달할 객체를 생성합니다. `updateTemplate` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create updateTemplate parameters
var params = {
  Template: {
    TemplateName: "TEMPLATE_NAME" /* required */,
    HtmlPart: "HTML_CONTENT",
    SubjectPart: "SUBJECT_LINE",
    TextPart: "TEXT_CONTENT",
  },
};

// Create the promise and SES service object
var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .updateTemplate(params)
  .promise();

// Handle promise's fulfilled/rejected states
templatePromise
  .then(function (data) {
    console.log("Template Updated");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 템플릿 세부 정보를 반환합니다.

```
node ses_updatetemplate.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_updatetemplate.js)에서 찾을 수 있습니다.

## 이메일 템플릿 삭제
<a name="ses-examples-delete-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다. 파일 이름이 `ses_deletetemplate.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`AWS.SES` 클라이언트 클래스의 `deleteTemplate` 메서드에 필수 `TemplateName` 파라미터를 전달할 객체를 생성합니다. `deleteTemplate` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .deleteTemplate({ TemplateName: "TEMPLATE_NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
templatePromise
  .then(function (data) {
    console.log("Template Deleted");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 템플릿 세부 정보를 반환합니다.

```
node ses_deletetemplate.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_deletetemplate.js)에서 찾을 수 있습니다.

# Amazon SES로 이메일 전송
<a name="ses-examples-sending-email"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 테스트 또는 HTML 이메일을 전송합니다.
+ 이메일 템플릿을 기반으로 이메일을 전송합니다.
+ 이메일 템플릿을 기반으로 대량 이메일을 전송합니다.

Amazon SES API에서는 이메일 메시지 작성에 대해 원하는 제어 정도에 따라 서식 지정 및 원시라는 두 가지 이메일 전송 방법을 선택할 수 있습니다. 자세한 내용은 [Amazon SES API를 사용하여 서식이 지정된 이메일 전송](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-formatted.html) 및 [Amazon SES API를 사용하여 원시 이메일 전송](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html) 섹션을 참조하세요.

## 시나리오
<a name="ses-examples-sending-email-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 다양한 방법으로 이메일을 전송합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `AWS.SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 템플릿을 생성하고 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendEmail-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendEmail-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendTemplatedEmail-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendTemplatedEmail-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendBulkTemplatedEmail-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#sendBulkTemplatedEmail-property)

## 사전 필수 작업
<a name="ses-examples-sending-emails-prerequisites"></a>
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 JSON 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 이메일 메시지 전송 요구 사항
<a name="ses-examples-sending-msail-reqs"></a>

Amazon SES에서는 이메일 메시지를 작성하는 즉시 전송 대기열에 넣습니다. `SES.sendEmail` 메서드를 사용하여 이메일을 전송하려면 메시지는 다음 요구 사항을 충족해야 합니다.
+ 확인된 이메일 주소 또는 도메인에서 메시지를 전송해야 합니다. 확인되지 않은 주소 또는 도메인을 사용하여 이메일을 전송하려고 시도하면 작업 결과로 `"Email address not verified"` 오류가 발생합니다.
+ 계정이 여전히 Amazon SES 샌드박스에 있는 경우 확인된 주소 또는 도메인으로만 또는 Amazon SES 메일박스 시뮬레이터와 연결된 이메일 주소로만 전송할 수 있습니다. 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [이메일 주소 및 도메인 확인](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html) 섹션을 참조하세요.
+ 첨부 파일을 포함한 메시지의 총 크기는 10MB 미만이어야 합니다.
+ 메시지에 최소 하나 이상의 수신자 이메일 주소가 포함되어야 합니다. 수신자 주소는 받는 사람: 주소, 참조: 주소 또는 숨은 참조: 주소일 수 있습니다. 수신자 이메일 주소가 잘못된 경우(즉, `UserName@[SubDomain.]Domain.TopLevelDomain` 형식이 아닌 경우) 올바른 다른 수신자가 메시지가 포함되더라도 전체 메시지가 거부됩니다.
+ 메시지에는 받는 사람:, 참조: 및 숨은 참조: 필드 전체에서 50명을 초과하는 수신자가 포함될 수 없습니다. 더 많은 대상에게 이메일 메시지를 전송해야 하는 경우 수신자 목록을 50명 이하의 여러 그룹으로 나눈 다음 `sendEmail` 메서드를 여러 번 호출하여 각 그룹에게 메시지를 전송할 수 있습니다.

## 이메일 전송
<a name="ses-examples-sendmail"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_sendemail.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

발신자 및 수신자 주소, 제목, 일반 텍스트 및 HTML 형식의 이메일 본문을 포함하여 전송할 이메일을 정의하는 파라미터 값을 `AWS.SES` 클라이언트 클래스의 `sendEmail` 메서드에 전달할 객체를 생성합니다. `sendEmail` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create sendEmail params
var params = {
  Destination: {
    /* required */
    CcAddresses: [
      "EMAIL_ADDRESS",
      /* more items */
    ],
    ToAddresses: [
      "EMAIL_ADDRESS",
      /* more items */
    ],
  },
  Message: {
    /* required */
    Body: {
      /* required */
      Html: {
        Charset: "UTF-8",
        Data: "HTML_FORMAT_BODY",
      },
      Text: {
        Charset: "UTF-8",
        Data: "TEXT_FORMAT_BODY",
      },
    },
    Subject: {
      Charset: "UTF-8",
      Data: "Test email",
    },
  },
  Source: "SENDER_EMAIL_ADDRESS" /* required */,
  ReplyToAddresses: [
    "EMAIL_ADDRESS",
    /* more items */
  ],
};

// Create the promise and SES service object
var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .sendEmail(params)
  .promise();

// Handle promise's fulfilled/rejected states
sendPromise
  .then(function (data) {
    console.log(data.MessageId);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES에서 전송할 이메일이 대기 상태로 전환됩니다.

```
node ses_sendemail.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_sendemail.js)에서 찾을 수 있습니다.

## 템플릿을 사용한 이메일 전송
<a name="ses-examples-sendtemplatedemail"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_sendtemplatedemail.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

발신자 및 수신자 주소, 제목, 일반 텍스트 및 HTML 형식의 이메일 본문을 포함하여 전송할 이메일을 정의하는 파라미터 값을 `AWS.SES` 클라이언트 클래스의 `sendTemplatedEmail` 메서드에 전달할 객체를 생성합니다. `sendTemplatedEmail` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create sendTemplatedEmail params
var params = {
  Destination: {
    /* required */
    CcAddresses: [
      "EMAIL_ADDRESS",
      /* more CC email addresses */
    ],
    ToAddresses: [
      "EMAIL_ADDRESS",
      /* more To email addresses */
    ],
  },
  Source: "EMAIL_ADDRESS" /* required */,
  Template: "TEMPLATE_NAME" /* required */,
  TemplateData: '{ "REPLACEMENT_TAG_NAME":"REPLACEMENT_VALUE" }' /* required */,
  ReplyToAddresses: ["EMAIL_ADDRESS"],
};

// Create the promise and SES service object
var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .sendTemplatedEmail(params)
  .promise();

// Handle promise's fulfilled/rejected states
sendPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES에서 전송할 이메일이 대기 상태로 전환됩니다.

```
node ses_sendtemplatedemail.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_sendtemplatedemail.js)에서 찾을 수 있습니다.

## 템플릿을 사용한 대량 이메일 전송
<a name="ses-examples-sendbulktemplatedemail"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_sendbulktemplatedemail.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

발신자 및 수신자 주소, 제목, 일반 텍스트 및 HTML 형식의 이메일 본문을 포함하여 전송할 이메일을 정의하는 파라미터 값을 `AWS.SES` 클라이언트 클래스의 `sendBulkTemplatedEmail` 메서드에 전달할 객체를 생성합니다. `sendBulkTemplatedEmail` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create sendBulkTemplatedEmail params
var params = {
  Destinations: [
    /* required */
    {
      Destination: {
        /* required */
        CcAddresses: [
          "EMAIL_ADDRESS",
          /* more items */
        ],
        ToAddresses: [
          "EMAIL_ADDRESS",
          "EMAIL_ADDRESS",
          /* more items */
        ],
      },
      ReplacementTemplateData: '{ "REPLACEMENT_TAG_NAME":"REPLACEMENT_VALUE" }',
    },
  ],
  Source: "EMAIL_ADDRESS" /* required */,
  Template: "TEMPLATE_NAME" /* required */,
  DefaultTemplateData: '{ "REPLACEMENT_TAG_NAME":"REPLACEMENT_VALUE" }',
  ReplyToAddresses: ["EMAIL_ADDRESS"],
};

// Create the promise and SES service object
var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .sendBulkTemplatedEmail(params)
  .promise();

// Handle promise's fulfilled/rejected states
sendPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.log(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES에서 전송할 이메일이 대기 상태로 전환됩니다.

```
node ses_sendbulktemplatedemail.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_sendbulktemplatedemail.js)에서 찾을 수 있습니다.

# Amazon SES에서 이메일 수신을 위한 IP 주소 필터 사용
<a name="ses-examples-ip-filters"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 특정 IP 주소 또는 특정 범위의 IP 주소에서 발신한 메일을 수락하거나 거부하기 위한 IP 주소 필터를 생성합니다.
+ 현재 IP 주소 필터를 나열합니다.
+ IP 주소 필터를 삭제합니다.

 Amazon SES에서 *필터*는 이름, IP 주소 범위, 해당 범위의 메일 허용 또는 차단 여부로 구성되는 데이터 구조입니다. 차단하거나 허용하려는 IP 주소는 CIDR(클래스 없는 도메인 간 라우팅) 표기법으로 단일 IP 주소 또는 IP 주소 범위로 지정됩니다. Amazon SES가 이메일을 수신하는 방법에 대한 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [Amazon SES 이메일 수신 개념](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-concepts.html) 섹션을 참조하세요.

## 시나리오
<a name="ses-examples-receiving-email-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 다양한 방법으로 이메일을 전송합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `AWS.SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 템플릿을 생성하고 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createReceiptFilter-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createReceiptFilter-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#listReceiptFilters-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#listReceiptFilters-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteReceiptFilter-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteReceiptFilter-property)

## 사전 필수 작업
<a name="ses-examples-ip-filters-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SDK 구성
<a name="ses-examples-ip-filters-configure-sdk"></a>

글로벌 구성 객체를 생성한 후 코드에 대한 리전을 설정하여 SDK for JavaScript를 구성합니다. 이 예제에서 리전이 `us-west-2`로 설정되어 있습니다.

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## IP 주소 필터 생성
<a name="ses-examples-ip-filters-creating"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_createreceiptfilter.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

필터 이름, 필터링할 IP 주소 또는 주소 범위, 필터링된 주소에서 오는 이메일 트래픽을 허용 또는 차단할지 여부를 포함하여 IP 필터를 정의하는 파라미터 값을 전달할 객체를 생성합니다. `createReceiptFilter` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create createReceiptFilter params
var params = {
  Filter: {
    IpFilter: {
      Cidr: "IP_ADDRESS_OR_RANGE",
      Policy: "Allow" | "Block",
    },
    Name: "NAME",
  },
};

// Create the promise and SES service object
var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .createReceiptFilter(params)
  .promise();

// Handle promise's fulfilled/rejected states
sendPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES에 필터가 생성됩니다.

```
node ses_createreceiptfilter.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_createreceiptfilter.js)에서 찾을 수 있습니다.

## IP 주소 필터 나열
<a name="ses-examples-ip-filters-listing"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_listreceiptfilters.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

비어 있는 파라미터 객체를 생성합니다. `listReceiptFilters` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .listReceiptFilters({})
  .promise();

// Handle promise's fulfilled/rejected states
sendPromise
  .then(function (data) {
    console.log(data.Filters);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 필터 목록을 반환합니다.

```
node ses_listreceiptfilters.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_listreceiptfilters.js)에서 찾을 수 있습니다.

## IP 주소 필터 삭제하기
<a name="ses-examples-ip-filters-deleting"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_deletereceiptfilter.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

삭제할 IP 필터의 이름을 전달할 객체를 생성합니다. `deleteReceiptFilter` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .deleteReceiptFilter({ FilterName: "NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
sendPromise
  .then(function (data) {
    console.log("IP Filter deleted");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES에서 필터가 삭제됩니다.

```
node ses_deletereceiptfilter.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_deletereceiptfilter.js)에서 찾을 수 있습니다.

# Amazon SES에서 수신 규칙 사용
<a name="ses-examples-receipt-rules"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 수신 규칙을 생성하고 삭제합니다.
+ 수신 규칙을 수신 규칙 세트로 정리합니다.

Amazon SES의 수신 규칙은 사용자 소유의 이메일 주소 또는 도메인으로 수신된 이메일을 어떻게 처리할지 지정합니다. *수신 규칙*에는 조건과 순서 지정된 작업 목록이 포함됩니다. 수신 이메일의 수신자가 수신 규칙의 조건에 지정된 수신자와 일치하는 경우 Amazon SES는 수신 규칙이 지정하는 작업을 수행합니다.

Amazon SES를 이메일 수신기로 사용하려면 하나 이상의 활성 *수신 규칙 세트*가 있어야 합니다. 수신 규칙 세트는 확인된 도메인 전체에서 수신하는 메일에 대해 Amazon SES가 수행해야 하는 작업을 지정하는 수신 규칙 모음으로, 순서가 지정되어 있습니다. 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [Amazon SES 이메일 수신 규칙 생성](Amazon Simple Email Service Developer Guidereceiving-email-receipt-rules.html) 및 [Amazon SES 이메일 수신 규칙 세트 생성](Amazon Simple Email Service Developer Guidereceiving-email-receipt-rule-set.html) 섹션을 참조하세요.

## 시나리오
<a name="ses-examples-receipt-rules-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 다양한 방법으로 이메일을 전송합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `AWS.SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 템플릿을 생성하고 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createReceiptRule-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createReceiptRule-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteReceiptRule-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteReceiptRule-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createReceiptRuleSet-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#createReceiptRuleSet-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteReceiptRuleSet-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SES.html#deleteReceiptRuleSet-property)

## 사전 필수 작업
<a name="ses-examples-receipt-rules-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 JSON 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## Amazon S3 수신 규칙 생성
<a name="ses-examples-creatingreceipt-rules"></a>

Amazon SES의 각 수신 규칙에는 순서가 지정된 작업 목록이 포함되어 있습니다. 이 예에서는 메일 메시지를 Amazon S3 버킷에 전송하는 Amazon S3 작업이 포함된 수신 규칙을 생성합니다. 수신 규칙 작업에 대한 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [작업 옵션](Amazon Simple Email Service Developer Guidereceiving-email-action.html) 섹션을 참조하세요.

Amazon SES가 Amazon S3 버킷에 이메일을 쓸 수 있도록 `PutObject` 권한을 Amazon SES에 부여하는 버킷 정책을 생성합니다. 이 버킷 정책 생성에 관한 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [Amazon SES에 S3 버킷에 작성할 수 있는 권한 부여](Amazon Simple Email Service Developer Guidereceiving-email-permissions.html#receiving-email-permissions-s3.html) 섹션을 참조하세요.

이 예에서는 Node.js 모듈을 사용해 Amazon SES에 수신 규칙을 생성하여 수신된 메시지를 Amazon S3 버킷에 저장합니다. 파일 이름이 `ses_createreceiptrule.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

수신 규칙 세트를 생성하는 데 필요한 값을 전달할 파라미터 객체를 생성합니다. `createReceiptRuleSet` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create createReceiptRule params
var params = {
  Rule: {
    Actions: [
      {
        S3Action: {
          BucketName: "S3_BUCKET_NAME",
          ObjectKeyPrefix: "email",
        },
      },
    ],
    Recipients: [
      "DOMAIN | EMAIL_ADDRESS",
      /* more items */
    ],
    Enabled: true | false,
    Name: "RULE_NAME",
    ScanEnabled: true | false,
    TlsPolicy: "Optional",
  },
  RuleSetName: "RULE_SET_NAME",
};

// Create the promise and SES service object
var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .createReceiptRule(params)
  .promise();

// Handle promise's fulfilled/rejected states
newRulePromise
  .then(function (data) {
    console.log("Rule created");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 수신 규칙을 생성합니다.

```
node ses_createreceiptrule.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_createreceiptrule.js)에서 찾을 수 있습니다.

## 수신 규칙 삭제하기
<a name="ses-examples-deletingreceipt-rules"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_deletereceiptrule.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

삭제할 수신 규칙의 이름을 전달할 파라미터 객체를 생성합니다. `deleteReceiptRule` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create deleteReceiptRule params
var params = {
  RuleName: "RULE_NAME" /* required */,
  RuleSetName: "RULE_SET_NAME" /* required */,
};

// Create the promise and SES service object
var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .deleteReceiptRule(params)
  .promise();

// Handle promise's fulfilled/rejected states
newRulePromise
  .then(function (data) {
    console.log("Receipt Rule Deleted");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 수신 규칙 세트 목록을 생성합니다.

```
node ses_deletereceiptrule.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_deletereceiptrule.js)에서 찾을 수 있습니다.

## 수신 규칙 세트 생성하기
<a name="ses-examples-creatingreceiptrulesets"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_createreceiptruleset.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

새 수신 규칙 세트의 이름을 전달할 파라미터 객체를 생성합니다. `createReceiptRuleSet` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .createReceiptRuleSet({ RuleSetName: "NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
newRulePromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 수신 규칙 세트 목록을 생성합니다.

```
node ses_createreceiptruleset.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_createreceiptruleset.js)에서 찾을 수 있습니다.

## 수신 규칙 세트 삭제하기
<a name="ses-examples-deletingreceiptrulesets"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_deletereceiptruleset.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

삭제할 수신 규칙 세트의 이름을 전달할 객체를 생성합니다. `deleeReceiptRuleSet` 메서드를 호출하려면 파라미터를 전달하는 Amazon SES 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the promise and SES service object
var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" })
  .deleteReceiptRuleSet({ RuleSetName: "NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
newRulePromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다. Amazon SES가 수신 규칙 세트 목록을 생성합니다.

```
node ses_deletereceiptruleset.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/ses/ses_deletereceiptruleset.js)에서 찾을 수 있습니다.

# Amazon Simple Notification Service 예
<a name="sns-examples"></a>

Amazon Simple Notification Service(Amazon SNS)는 구독 중인 엔드포인트 또는 클라이언트에 대한 메시지 전달 또는 전송을 조정 및 관리하는 웹 서비스입니다.

Amazon SNS에는 게시자와 구독자 또는 생산자와 소비자라고 하는 두 가지 클라이언트 유형이 있습니다.

![\[JavaScript 환경, SDK, Amazon SNS 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-sns.png)


게시자는 주제에 대한 메시지를 생산 및 발송함으로써 구독자와 비동시적으로 통신하는 논리적 액세스 및 커뮤니케이션 채널입니다. 구독자(웹 서버, 이메일 주소, Amazon SQS 대기열, Lambda 함수)는 주제를 구독할 때 지원되는 프로토콜(Amazon SQS, HTTP/S, 이메일, SMS, AWS Lambda) 중 하나를 통해 메시지 또는 알림을 소비하거나 수신합니다.

Amazon SNS용 JavaScript API는 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html)를 통해 노출됩니다.

**Topics**
+ [Amazon SNS에서 주제 관리](sns-examples-managing-topics.md)
+ [Amazon SNS에서 메시지 게시](sns-examples-publishing-messages.md)
+ [Amazon SNS에서 구독 관리](sns-examples-subscribing-unubscribing-topics.md)
+ [Amazon SNS를 통한 SMS 메시지 전송](sns-examples-sending-sms.md)

# Amazon SNS에서 주제 관리
<a name="sns-examples-managing-topics"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SNS에서 알림을 게시할 수 있는 주제를 생성하는 방법
+ Amazon SNS에서 생성된 주제를 삭제하는 방법
+ 사용 가능한 주제 목록을 가져오는 방법.
+ 주제 속성을 가져오고 설정하는 방법.

## 시나리오
<a name="sns-examples-managing-topics-scenario"></a>

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SNS 주제를 생성, 나열 및 삭제하고 주제 속성을 처리합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SNS` 클라이언트 클래스의 다음 메서드를 사용하여 주제를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#createTopic-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#createTopic-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#listTopics-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#listTopics-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#deleteTopic-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#deleteTopic-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#getTopicAttributes-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#getTopicAttributes-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setTopicAttributes-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setTopicAttributes-property)

## 사전 필수 작업
<a name="sns-examples-managing-topics-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](http://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 JSON 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 주제 생성
<a name="sns-examples-managing-topics-createtopic"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS 주제를 생성합니다. 파일 이름이 `sns_createtopic.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`Name` 클라이언트 클래스의 `createTopic` 메서드에 새 주제의 `AWS.SNS`을 전달할 객체를 생성합니다. `createTopic` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다. promise에서 반환되는 `data`에는 주제의 ARN이 포함됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var createTopicPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .createTopic({ Name: "TOPIC_NAME" })
  .promise();

// Handle promise's fulfilled/rejected states
createTopicPromise
  .then(function (data) {
    console.log("Topic ARN is " + data.TopicArn);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_createtopic.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_createtopic.js)에서 찾을 수 있습니다.

## 주제 나열
<a name="sns-examples-managing-topics-listtopics"></a>

이 예에서는 Node.js 모듈을 사용하여 모든 Amazon SNS 주제를 나열합니다. 파일 이름이 `sns_listtopics.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`listTopics` 클라이언트 클래스의 `AWS.SNS` 메서드에 전달할 비어 있는 객체를 생성합니다. `listTopics` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다. promise에서 반환되는 `data`에는 주제 ARN의 배열이 포함됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var listTopicsPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .listTopics({})
  .promise();

// Handle promise's fulfilled/rejected states
listTopicsPromise
  .then(function (data) {
    console.log(data.Topics);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_listtopics.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_listtopics.js)에서 찾을 수 있습니다.

## 주제 삭제
<a name="sns-examples-managing-topics-deletetopic"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS 주제를 삭제합니다. 파일 이름이 `sns_deletetopic.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`TopicArn` 클라이언트 클래스의 `deleteTopic` 메서드에 전달할 삭제할 주제의 `AWS.SNS`을 포함하는 객체를 생성합니다. `deleteTopic` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var deleteTopicPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .deleteTopic({ TopicArn: "TOPIC_ARN" })
  .promise();

// Handle promise's fulfilled/rejected states
deleteTopicPromise
  .then(function (data) {
    console.log("Topic Deleted");
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_deletetopic.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_deletetopic.js)에서 찾을 수 있습니다.

## 주제 속성 가져오기
<a name="sns-examples-managing-topicsgetttopicattributes"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS 주제의 속성을 검색합니다. 파일 이름이 `sns_gettopicattributes.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`TopicArn` 클라이언트 클래스의 `getTopicAttributes` 메서드에 전달할 삭제할 주제의 `AWS.SNS`을 포함하는 객체를 생성합니다. `getTopicAttributes` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var getTopicAttribsPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .getTopicAttributes({ TopicArn: "TOPIC_ARN" })
  .promise();

// Handle promise's fulfilled/rejected states
getTopicAttribsPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_gettopicattributes.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_gettopicattributes.js)에서 찾을 수 있습니다.

## 주제 속성 설정
<a name="sns-examples-managing-topicsstttopicattributes"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS 주제의 변경 가능한 속성을 설정합니다. 파일 이름이 `sns_settopicattributes.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

속성을 설정하려고 하는 주제의 `TopicArn`, 설정할 속성의 이름, 해당 속성의 새 값을 포함하여 속성 업데이트를 위한 파라미터를 포함하는 객체를 생성합니다. `Policy`, `DisplayName` 및 `DeliveryPolicy` 속성만 설정할 수 있습니다. `setTopicAttributes` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다. `setTopicAttributes` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create setTopicAttributes parameters
var params = {
  AttributeName: "ATTRIBUTE_NAME" /* required */,
  TopicArn: "TOPIC_ARN" /* required */,
  AttributeValue: "NEW_ATTRIBUTE_VALUE",
};

// Create promise and SNS service object
var setTopicAttribsPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .setTopicAttributes(params)
  .promise();

// Handle promise's fulfilled/rejected states
setTopicAttribsPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_settopicattributes.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_settopicattributes.js)에서 찾을 수 있습니다.

# Amazon SNS에서 메시지 게시
<a name="sns-examples-publishing-messages"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SNS 주제에 메시지를 게시하는 방법

## 시나리오
<a name="sns-examples-publishing-messages-scenario"></a>

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SNS의 메시지를 주제 엔드포인트, 이메일 또는 전화번호에 게시합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SNS` 클라이언트 클래스의 다음 메서드를 사용하여 메시지를 전송합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property)

## 사전 필수 작업
<a name="sns-examples-publishing-messages-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](http://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 JSON 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## Amazon SNS 주제에 메시지 게시
<a name="sns-examples-publishing-text-messages"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS 주제에 메시지를 게시합니다. 파일 이름이 `sns_publishtotopic.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

메시지 텍스트 및 Amazon SNS 주제의 ARN을 포함하여 메시지를 게시하기 위한 파라미터를 포함하는 객체를 생성합니다. 사용 가능한 SMS 속성에 대한 세부 정보는 [SetSMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setSMSAttributes-property)를 참조하세요.

`publish` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다. 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 response를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create publish parameters
var params = {
  Message: "MESSAGE_TEXT" /* required */,
  TopicArn: "TOPIC_ARN",
};

// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .publish(params)
  .promise();

// Handle promise's fulfilled/rejected states
publishTextPromise
  .then(function (data) {
    console.log(
      `Message ${params.Message} sent to the topic ${params.TopicArn}`
    );
    console.log("MessageID is " + data.MessageId);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_publishtotopic.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_publishtotopic.js)에서 찾을 수 있습니다.

# Amazon SNS에서 구독 관리
<a name="sns-examples-subscribing-unubscribing-topics"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SNS 주제의 모든 구독을 나열하는 방법
+ 이메일 주소, 애플리케이션 엔드포인트 또는 AWS Lambda 함수에서 Amazon SNS 주제를 구독하는 방법
+ Amazon SNS 주제의 구독을 취소하는 방법

## 시나리오
<a name="sns-examples-subscribing-unubscribing-yopics-scenario"></a>

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SNS 주제에 알림 메시지를 게시합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SNS` 클라이언트 클래스의 다음 메서드를 사용하여 주제를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#subscribe-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#subscribe-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#confirmSubscription-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#confirmSubscription-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#listSubscriptionsByTopic-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#listSubscriptionsByTopic-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#unsubscribe-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#unsubscribe-property)

## 사전 필수 작업
<a name="sns-examples-subscribing-unubscribing-topics-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](http://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 JSON 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 주제에 대한 구독 나열
<a name="sns-examples-list-subscriptions-email"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS 주제에 대한 모든 구독을 나열합니다. 파일 이름이 `sns_listsubscriptions.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

구독을 나열할 주제에 대한 `TopicArn` 파라미터를 포함하는 객체를 생성합니다. `listSubscriptionsByTopic` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다. `listSubscriptionsByTopic` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

const params = {
  TopicArn: "TOPIC_ARN",
};

// Create promise and SNS service object
var subslistPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .listSubscriptionsByTopic(params)
  .promise();

// Handle promise's fulfilled/rejected states
subslistPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_listsubscriptions.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_listsubscriptions.js)에서 찾을 수 있습니다.

## 이메일 주소에서 주제 구독
<a name="sns-examples-subscribing-email"></a>

이 예에서는 Node.js 모듈을 사용하여 이메일 주소에서 Amazon SNS 주제의 SMTP 이메일 메시지를 수신하도록 이메일 주소에서 주제를 구독합니다. 파일 이름이 `sns_subscribeemail.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`Protocol` 프로토콜, 구독할 주제의 `email`, 메시지 `TopicArn`로 사용되는 이메일 주소를 지정하기 위한 `Endpoint` 파라미터를 포함하는 객체를 생성합니다. `subscribe` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다. 이 항목의 다른 예에 나와 있듯이, `subscribe` 메서드를 사용하면 전달된 파라미터에 사용되는 값에 따라 여러 다양한 엔드포인트에서 Amazon SNS 주제를 구독할 수 있습니다.

`subscribe` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create subscribe/email parameters
var params = {
  Protocol: "EMAIL" /* required */,
  TopicArn: "TOPIC_ARN" /* required */,
  Endpoint: "EMAIL_ADDRESS",
};

// Create promise and SNS service object
var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .subscribe(params)
  .promise();

// Handle promise's fulfilled/rejected states
subscribePromise
  .then(function (data) {
    console.log("Subscription ARN is " + data.SubscriptionArn);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_subscribeemail.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_subscribeemail.js)에서 찾을 수 있습니다.

## 애플리케이션 엔드포인트에서 주제 구독
<a name="sns-examples-subscribing-apps"></a>

이 예에서는 Node.js 모듈을 사용하여 모바일 애플리케이션 엔드포인트에서 Amazon SNS 주제의 알림을 수신하도록 모바일 애플리케이션 엔드포인트에서 주제를 구독합니다. 파일 이름이 `sns_subscribeapp.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`Protocol` 프로토콜, 구독할 주제의 `application`, `TopicArn` 파라미터에 대한 모바일 애플리케이션 엔드포인트의 ARN을 지정하기 위한 `Endpoint` 파라미터를 포함하는 객체를 생성합니다. `subscribe` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다.

`subscribe` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create subscribe/email parameters
var params = {
  Protocol: "application" /* required */,
  TopicArn: "TOPIC_ARN" /* required */,
  Endpoint: "MOBILE_ENDPOINT_ARN",
};

// Create promise and SNS service object
var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .subscribe(params)
  .promise();

// Handle promise's fulfilled/rejected states
subscribePromise
  .then(function (data) {
    console.log("Subscription ARN is " + data.SubscriptionArn);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_subscribeapp.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_subscribeapp.js)에서 찾을 수 있습니다.

## Lambda 함수에서 주제 구독
<a name="sns-examples-subscribing-lambda"></a>

이 예에서는 Node.js 모듈을 사용하여 AWS Lambda 함수에서 Amazon SNS 주제의 알림을 수신하도록 Lambda 함수에서 주제를 구독합니다. 파일 이름이 `sns_subscribelambda.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

`Protocol` 프로토콜, 구독할 주제의 `lambda`, `TopicArn` 파라미터로 사용되는 AWS Lambda 함수의 ARN을 지정하는 `Endpoint` 파라미터를 포함하는 객체를 생성합니다. `subscribe` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다.

`subscribe` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create subscribe/email parameters
var params = {
  Protocol: "lambda" /* required */,
  TopicArn: "TOPIC_ARN" /* required */,
  Endpoint: "LAMBDA_FUNCTION_ARN",
};

// Create promise and SNS service object
var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .subscribe(params)
  .promise();

// Handle promise's fulfilled/rejected states
subscribePromise
  .then(function (data) {
    console.log("Subscription ARN is " + data.SubscriptionArn);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_subscribelambda.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_subscribelambda.js)에서 찾을 수 있습니다.

## 주제의 구독 취소
<a name="sns-examples-unsubscribing"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS 주제 구독을 취소합니다. 파일 이름이 `sns_unsubscribe.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

구독 해제할 구독의 ARN을 지정하는 `SubscriptionArn` 파라미터를 포함하는 객체를 생성합니다. `unsubscribe` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다.

`unsubscribe` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .unsubscribe({ SubscriptionArn: TOPIC_SUBSCRIPTION_ARN })
  .promise();

// Handle promise's fulfilled/rejected states
subscribePromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_unsubscribe.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_unsubscribe.js)에서 찾을 수 있습니다.

# Amazon SNS를 통한 SMS 메시지 전송
<a name="sns-examples-sending-sms"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SNS에 대한 SMS 메시징 기본 설정을 가져오고 설정하는 방법
+ 전화번호를 점검하여 SMS 메시지 수신을 옵트아웃했는지 여부를 확인하는 방법.
+ SMS 메시지 수신을 옵트아웃한 전화번호의 목록을 가져오는 방법.
+ SMS 메시지를 전송하는 방법.

## 시나리오
<a name="sns-examples-sending-sms-scenario"></a>

사용자는 Amazon SNS를 사용하여 SMS 수신 가능한 디바이스에 문자 메시지 또는 SMS 메시지를 전송할 수 있습니다. 전화번호로 메시지를 직접 전송할 수 있으며, 전화번호에서 주제를 구독하고 메시지를 주제로 전송하여 메시지를 여러 전화번호로 한 번에 전송할 수 있습니다.

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SNS의 SMS 문자 메시지를 SMS 지원 디바이스에 게시합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SNS` 클라이언트 클래스의 다음 메서드를 사용하여 SMS 메시지를 게시합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#getSMSAttributes-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#getSMSAttributes-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setSMSAttributes-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setSMSAttributes-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#checkIfPhoneNumberIsOptedOut-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#checkIfPhoneNumberIsOptedOut-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#listPhoneNumbersOptedOut-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#listPhoneNumbersOptedOut-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property)

## 사전 필수 작업
<a name="sns-examples-sending-sms-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](http://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 자격 증명 JSON 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## SMS 속성 가져오기
<a name="sending-sms-getattributes"></a>

Amazon SNS를 사용하여 전송을 최적화하는 방법(비용 또는 안정성 있는 전송), 월 지출 한도, 메시지 전송을 로깅하는 방법, 일일 SMS 사용 보고서를 구독하는지 여부 등 SMS 메시징에 대한 기본 설정을 지정합니다. 이러한 기본 설정을 검색하여 Amazon SNS의 SMS 속성으로 설정합니다.

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS에서 현재 SMS 속성을 가져옵니다. 파일 이름이 `sns_getsmstype.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. 가져올 개별 속성의 이름을 포함하여 SMS 속성을 가져오기 위한 파라미터를 포함하는 객체를 생성합니다. 사용 가능한 SMS 속성에 대한 자세한 내용은 Amazon Simple Notification Service API 참조의 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)를 참조하세요.

이 예제에서는 SMS 메시지를 최저 비용이 발생하도록 메시지 전송을 최적화하는 `DefaultSMSType`로 전송할지 또는 최고 안정성을 달성하도록 메시지 전송을 최적화하는 `Promotional`로 전송할지를 제어하는 `Transactional` 속성을 가져옵니다. `setTopicAttributes` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다. `getSMSAttributes` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create SMS Attribute parameter you want to get
var params = {
  attributes: [
    "DefaultSMSType",
    "ATTRIBUTE_NAME",
    /* more items */
  ],
};

// Create promise and SNS service object
var getSMSTypePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .getSMSAttributes(params)
  .promise();

// Handle promise's fulfilled/rejected states
getSMSTypePromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_getsmstype.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_getsmstype.js)에서 찾을 수 있습니다.

## SMS 속성 설정
<a name="sending-sms-setattributes"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS에서 현재 SMS 속성을 가져옵니다. 파일 이름이 `sns_setsmstype.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. 설정할 개별 속성의 이름과 각 속성에 설정할 값을 포함하여 SMS 속성을 설정하기 위한 파라미터를 포함하는 객체를 생성합니다. 사용 가능한 SMS 속성에 대한 자세한 내용은 Amazon Simple Notification Service API 참조의 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)를 참조하세요.

다음 예제에서는 `DefaultSMSType` 속성을 `Transactional`로 설정하여 최고의 안정성을 달성하도록 메시지 전송을 최적화합니다. `setTopicAttributes` 클라이언트 클래스의 `AWS.SNS` 메서드에 파라미터를 전달합니다. `getSMSAttributes` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create SMS Attribute parameters
var params = {
  attributes: {
    /* required */
    DefaultSMSType: "Transactional" /* highest reliability */,
    //'DefaultSMSType': 'Promotional' /* lowest cost */
  },
};

// Create promise and SNS service object
var setSMSTypePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .setSMSAttributes(params)
  .promise();

// Handle promise's fulfilled/rejected states
setSMSTypePromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_setsmstype.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_setsmstype.js)에서 찾을 수 있습니다.

## 전화번호가 옵트아웃되었는지 여부 확인
<a name="sending-sms-checkifphonenumberisoptedout"></a>

이 예제에서는 Node.js 모듈을 사용하여 전화 번호가 SMS 메시지 수신에서 옵트아웃되었는지 여부를 확인합니다. 파일 이름이 `sns_checkphoneoptout.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. 파라미터로 확인할 전화번호를 포함하는 객체를 생성합니다.

이 예제에서는 확인할 전화번호를 지정하는 `PhoneNumber` 파라미터를 설정합니다. `checkIfPhoneNumberIsOptedOut` 클라이언트 클래스의 `AWS.SNS` 메서드에 객체를 전달합니다. `checkIfPhoneNumberIsOptedOut` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var phonenumPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .checkIfPhoneNumberIsOptedOut({ phoneNumber: "PHONE_NUMBER" })
  .promise();

// Handle promise's fulfilled/rejected states
phonenumPromise
  .then(function (data) {
    console.log("Phone Opt Out is " + data.isOptedOut);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_checkphoneoptout.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_checkphoneoptout.js)에서 찾을 수 있습니다.

## 옵트아웃된 전화번호 나열
<a name="sending-sms-listphonenumbersoptedout"></a>

이 예제에서는 Node.js 모듈을 사용하여 SMS 메시지 수신에서 옵트아웃한 전화번호의 목록을 가져옵니다. 파일 이름이 `sns_listnumbersoptedout.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. 비어 있는 객체를 파라미터로 생성합니다.

`listPhoneNumbersOptedOut` 클라이언트 클래스의 `AWS.SNS` 메서드에 객체를 전달합니다. `listPhoneNumbersOptedOut` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var phonelistPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .listPhoneNumbersOptedOut({})
  .promise();

// Handle promise's fulfilled/rejected states
phonelistPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_listnumbersoptedout.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_listnumbersoptedout.js)에서 찾을 수 있습니다.

## SMS 메시지 게시
<a name="sending-sms-publishsms"></a>

이 예제에서는 Node.js 모듈을 사용하여 SMS 메시지를 전화번호에 전송합니다. 파일 이름이 `sns_publishsms.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. `Message` 및 `PhoneNumber` 파라미터를 포함하는 객체를 생성합니다.

SMS 메시지를 전송할 때 E.164 형식을 사용하여 전화번호를 지정합니다. E.164는 국제 통신에 사용되는 전화번호 구조의 표준입니다. 이 형식을 따르는 전화번호는 최대 15자리 숫자를 사용할 수 있으며 더하기 문자(\$1) 및 국가 코드가 접두사로 추가됩니다. 예를 들어, E.164 형식의 미국 전화번호는 \$11001XXX5550100으로 표시될 수 있습니다.

이 예제에서는 메시지를 전송할 전화번호를 지정하는 `PhoneNumber` 파라미터를 설정합니다. `publish` 클라이언트 클래스의 `AWS.SNS` 메서드에 객체를 전달합니다. `publish` 메서드를 직접 호출하려면 파라미터 객체를 전달하는 Amazon SNS 서비스 객체를 간접 호출하기 위한 promise를 생성합니다. 그런 다음 promise 콜백에서 `response`를 처리합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create publish parameters
var params = {
  Message: "TEXT_MESSAGE" /* required */,
  PhoneNumber: "E.164_PHONE_NUMBER",
};

// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .publish(params)
  .promise();

// Handle promise's fulfilled/rejected states
publishTextPromise
  .then(function (data) {
    console.log("MessageID is " + data.MessageId);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sns_publishsms.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sns/sns_publishsms.js)에서 찾을 수 있습니다.

# Amazon SQS 예제
<a name="sqs-examples"></a>

Amazon Simple Queue Service(Amazon SQS)는 빠르고 안정적이며 확장 가능한 완전관리형 메시지 대기열 서비스입니다. Amazon SQS를 사용하면 클라우드 애플리케이션의 구성 요소를 분리할 수 있습니다. Amazon SQS에는 높은 처리량과 최소 1회 처리 기능을 갖춘 표준 대기열과 선입선출(FIFO) 전송 및 정확히 1회 처리를 제공하는 FIFO 대기열이 포함되어 있습니다.

![\[JavaScript 환경, SDK, Amazon S3 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/code-samples-sqs.png)


Amazon SQS용 JavaScript API는 `AWS.SQS` 클라이언트 클래스를 통해 노출됩니다. Amazon SQS 클라이언트 클래스 사용에 대한 자세한 내용은 API 참조의 [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html) 섹션을 참조하세요.

**Topics**
+ [Amazon SQS에서 대기열 사용](sqs-examples-using-queues.md)
+ [Amazon SQS에서 메시지 전송 및 수신](sqs-examples-send-receive-messages.md)
+ [Amazon SQS의 제한 시간 초과 관리](sqs-examples-managing-visibility-timeout.md)
+ [Amazon SQS에서 긴 폴링 활성화](sqs-examples-enable-long-polling.md)
+ [Amazon SQS에서 DLQ(Dead Letter Queue) 사용](sqs-examples-dead-letter-queues.md)

# Amazon SQS에서 대기열 사용
<a name="sqs-examples-using-queues"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 모든 메시지 대기열의 목록을 가져오는 방법
+ 특정 대기열의 URL을 획득하는 방법
+ 대기열을 생성하고 삭제하는 방법

## 예제 소개
<a name="sqs-examples-using-queues-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 대기열을 작업합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SQS` 클라이언트 클래스의 다음 메서드를 직접 호출하기 위해 대기열을 활성화합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#listQueues-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#listQueues-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#createQueue-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#createQueue-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#getQueueUrl-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#getQueueUrl-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#deleteQueue-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#deleteQueue-property)

Amazon SQS 메시지에 대한 자세한 정보는 *Amazon Simple Queue Service 개발자 안내서*의 [대기열의 작동 방식](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-how-it-works.html)을 참조하세요.

## 사전 필수 작업
<a name="sqs-examples-using-queues-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 대기열 목록 표시
<a name="sqs-examples-using-queues-listing-queues"></a>

파일 이름이 `sqs_listqueues.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 대기열 목록을 표시하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체는 기본적으로 비어 있는 객체입니다. `listQueues` 메서드를 호출하여 대기열 목록을 검색합니다. 콜백에서 모든 대기열의 URL이 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {};

sqs.listQueues(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrls);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_listqueues.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_listqueues.js)에서 찾을 수 있습니다.

## 대기열 만들기
<a name="sqs-examples-using-queues-create-queue"></a>

파일 이름이 `sqs_createqueue.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 대기열 목록을 표시하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 생성된 대기열의 이름이 포함되어야 합니다. 파라미터에는 메시지 전송이 지연되는 시간(초) 또는 수신한 메시지를 보관할 시간(초)과 같은 대기열의 속성도 포함될 수 있습니다. `createQueue` 메서드를 호출합니다. 콜백에서 생성된 대기열의 URL이 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueName: "SQS_QUEUE_NAME",
  Attributes: {
    DelaySeconds: "60",
    MessageRetentionPeriod: "86400",
  },
};

sqs.createQueue(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrl);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_createqueue.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_createqueue.js)에서 찾을 수 있습니다.

## 대기열의 URL 가져오기
<a name="sqs-examples-using-queues-get-queue-url"></a>

파일 이름이 `sqs_getqueueurl.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 대기열 목록을 표시하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체에는 URL을 가져올 대기열의 이름이 포함되어야 합니다. `getQueueUrl` 메서드를 호출합니다. 콜백에서 지정된 대기열의 URL이 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueName: "SQS_QUEUE_NAME",
};

sqs.getQueueUrl(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrl);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_getqueueurl.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_getqueueurl.js)에서 찾을 수 있습니다.

## 대기열 삭제
<a name="sqs-examples-using-queues-delete-queue"></a>

파일 이름이 `sqs_deletequeue.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 대기열을 삭제하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 객체는 삭제하려는 대기열의 URL로 구성됩니다. `deleteQueue` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueUrl: "SQS_QUEUE_URL",
};

sqs.deleteQueue(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_deletequeue.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_deletequeue.js)에서 찾을 수 있습니다.

# Amazon SQS에서 메시지 전송 및 수신
<a name="sqs-examples-send-receive-messages"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 대기열에 있는 메시지를 전송하는 방법.
+ 대기열에 있는 메시지를 수신하는 방법.
+ 대기열에 있는 메시지를 삭제하는 방법.

## 시나리오
<a name="sqs-examples-send-receive-messages-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 메시지를 전송하고 수신합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SQS` 클라이언트 클래스의 다음 메서드를 사용하여 메시지를 전송하고 수신합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessage-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessage-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#receiveMessage-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#receiveMessage-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#deleteMessage-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#deleteMessage-property)

Amazon SQS 메시지에 대한 자세한 내용은 *Amazon Simple Queue Service 개발자 안내서*의 [Amazon SQS 대기열로 메시지 전송](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-send-message.html) 및 [Amazon SQS 대기열에서 메시지 수신 및 삭제](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-receive-delete-message.html)를 참조하세요.

## 사전 필수 작업
<a name="sqs-examples-send-receive-messages-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ Amazon SQS 대기열을 생성합니다. 대기열 생성에 대한 예제는 [Amazon SQS에서 대기열 사용](sqs-examples-using-queues.md) 섹션을 참조하세요.

## 대기열로 메시지 전송
<a name="sqs-examples-send-receive-messages-sending"></a>

파일 이름이 `sqs_sendmessage.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 이 메시지를 전송하려는 대기열의 URL을 포함하여 메시지에 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서 메시지는 제목, 저자, 목록에 속해 있는 기간(주)을 포함하여 소설 베스트셀러 목록에 있는 책에 대한 세부 정보를 제공합니다.

`sendMessage` 메서드를 호출합니다. 콜백에서 메시지의 고유 ID가 반환됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  // Remove DelaySeconds parameter and value for FIFO queues
  DelaySeconds: 10,
  MessageAttributes: {
    Title: {
      DataType: "String",
      StringValue: "The Whistler",
    },
    Author: {
      DataType: "String",
      StringValue: "John Grisham",
    },
    WeeksOn: {
      DataType: "Number",
      StringValue: "6",
    },
  },
  MessageBody:
    "Information about current NY Times fiction bestseller for week of 12/11/2016.",
  // MessageDeduplicationId: "TheWhistler",  // Required for FIFO queues
  // MessageGroupId: "Group1",  // Required for FIFO queues
  QueueUrl: "SQS_QUEUE_URL",
};

sqs.sendMessage(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.MessageId);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_sendmessage.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_sendmessage.js)에서 찾을 수 있습니다.

## 대기열에서 메시지 수신 및 삭제
<a name="sqs-examples-send-receive-messages-receiving"></a>

파일 이름이 `sqs_receivemessage.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 메시지를 수신하려는 대기열의 URL을 포함하여 메시지에 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서 파라미터는 모든 메시지 속성의 수신 및 10개 이하의 메시지 수신을 지정합니다.

`receiveMessage` 메서드를 호출합니다. 콜백에서 나중에 해당 메시지를 삭제하기 위해 사용하는 각 메시지의 `ReceiptHandle`을 검색할 수 있는 `Message` 객체의 배열이 반환됩니다. 메시지를 삭제하는 데 필요한 파라미터를 포함하는 또 다른 JSON 객체를 생성합니다. 이 파라미터는 대기열의 URL 및 `ReceiptHandle` 값입니다. `deleteMessage` 메서드를 호출하여 수신한 메시지를 삭제합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var queueURL = "SQS_QUEUE_URL";

var params = {
  AttributeNames: ["SentTimestamp"],
  MaxNumberOfMessages: 10,
  MessageAttributeNames: ["All"],
  QueueUrl: queueURL,
  VisibilityTimeout: 20,
  WaitTimeSeconds: 0,
};

sqs.receiveMessage(params, function (err, data) {
  if (err) {
    console.log("Receive Error", err);
  } else if (data.Messages) {
    var deleteParams = {
      QueueUrl: queueURL,
      ReceiptHandle: data.Messages[0].ReceiptHandle,
    };
    sqs.deleteMessage(deleteParams, function (err, data) {
      if (err) {
        console.log("Delete Error", err);
      } else {
        console.log("Message Deleted", data);
      }
    });
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_receivemessage.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_receivemessage.js)에서 찾을 수 있습니다.

# Amazon SQS의 제한 시간 초과 관리
<a name="sqs-examples-managing-visibility-timeout"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 대기열에서 수신된 메시지를 볼 수 없는 시간 간격을 지정하는 방법

## 시나리오
<a name="sqs-examples-managing-visibility-timeout-scenario"></a>

이 예제에서는 Node.js 모듈을 사용하여 제한 시간 초과를 관리합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SQS` 클라이언트 클래스의 다음 메서드를 사용하여 제한 시간 초과를 관리합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#changeMessageVisibility-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#changeMessageVisibility-property)

Amazon SQS 가시성 제한 시간에 대한 자세한 정보는 *Amazon Simple Queue Service 개발자 안내서*의 [제한 시간 초과](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html)를 참조하세요.

## 사전 필수 작업
<a name="sqs-examples-managing-visibility-timeout-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ Amazon SQS 대기열을 생성합니다. 대기열 생성에 대한 예제는 [Amazon SQS에서 대기열 사용](sqs-examples-using-queues.md) 섹션을 참조하세요.
+ 대기열로 메시지를 전송합니다. 대기열로 메시지를 전송하는 방법에 대한 예제는 [Amazon SQS에서 메시지 전송 및 수신](sqs-examples-send-receive-messages.md) 섹션을 참조하세요.

## 제한 시간 초과 변경
<a name="sqs-examples-managing-visibility-timeout-setting"></a>

파일 이름이 `sqs_changingvisibility.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon Simple Queue Service에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 대기열에서 메시지를 검색합니다.

대기열에서 메시지를 수신하면 메시지가 포함된 대기열의 URL, 메시지를 수신할 때 반환된 `ReceiptHandle`, 새 제한 시간(초)을 포함하여 제한 시간을 설정하기 위해 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `changeMessageVisibility` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region to us-west-2
AWS.config.update({ region: "us-west-2" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var queueURL = "https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME";

var params = {
  AttributeNames: ["SentTimestamp"],
  MaxNumberOfMessages: 1,
  MessageAttributeNames: ["All"],
  QueueUrl: queueURL,
};

sqs.receiveMessage(params, function (err, data) {
  if (err) {
    console.log("Receive Error", err);
  } else {
    // Make sure we have a message
    if (data.Messages != null) {
      var visibilityParams = {
        QueueUrl: queueURL,
        ReceiptHandle: data.Messages[0].ReceiptHandle,
        VisibilityTimeout: 20, // 20 second timeout
      };
      sqs.changeMessageVisibility(visibilityParams, function (err, data) {
        if (err) {
          console.log("Delete Error", err);
        } else {
          console.log("Timeout Changed", data);
        }
      });
    } else {
      console.log("No messages to change");
    }
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_changingvisibility.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_changingvisibility.js)에서 찾을 수 있습니다.

# Amazon SQS에서 긴 폴링 활성화
<a name="sqs-examples-enable-long-polling"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 새로 생성된 대기열에 대해 긴 폴링을 활성화하는 방법
+ 기존 대기열에 대해 긴 폴링을 활성화하는 방법
+ 메시지를 수신할 때 긴 폴링을 활성화하는 방법.

## 시나리오
<a name="sqs-examples-enable-long-polling-scenario"></a>

긴 폴링은 응답을 전송하기 전에 대기열에서 메시지를 사용할 수 있을 때까지 Amazon SQS를 지정된 시간 동안 대기시켜 빈 응답의 개수를 줄입니다. 또한, 긴 폴링은 서버의 샘플링 대신에 모든 서버를 쿼리하여 False인 빈 응답을 제거합니다. 긴 폴링을 활성화하려면 수신된 메시지에 0이 아닌 대기 시간을 지정해야 합니다. 이렇게 하려면 대기열의 `ReceiveMessageWaitTimeSeconds` 파라미터를 설정하거나 메시지가 수신되었을 때 메시지에서 `WaitTimeSeconds` 파라미터를 설정하면 됩니다.

이 예제에서는 일련의 Node.js 모듈을 사용하여 긴 폴링을 활성화합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SQS` 클라이언트 클래스의 다음 메서드를 사용하여 긴 폴링을 활성화합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#setQueueAttributes-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#setQueueAttributes-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#receiveMessage-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#receiveMessage-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#createQueue-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#createQueue-property)

Amazon SQS 긴 폴링에 대한 자세한 내용은 *Amazon Simple Queue Service 개발자 안내서*의 [긴 폴링](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html)을 참조하세요.

## 사전 필수 작업
<a name="sqs-examples-enable-long-polling-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.

## 대기열 생성 시 긴 폴링 활성화
<a name="sqs-examples-enable-long-polling-on-queue-creation"></a>

파일 이름이 `sqs_longpolling_createqueue.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. `ReceiveMessageWaitTimeSeconds` 파라미터의 0이 아닌 값을 포함하여 대기열을 생성하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `createQueue` 메서드를 호출합니다. 그러면 대기열에 대해 긴 폴링이 활성화됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueName: "SQS_QUEUE_NAME",
  Attributes: {
    ReceiveMessageWaitTimeSeconds: "20",
  },
};

sqs.createQueue(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrl);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_longpolling_createqueue.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_longpolling_createqueue.js)에서 찾을 수 있습니다.

## 기존 대기열에 대해 긴 폴링 활성화
<a name="sqs-examples-enable-long-polling-existing-queue"></a>

파일 이름이 `sqs_longpolling_existingqueue.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon Simple Queue Service에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. `ReceiveMessageWaitTimeSeconds` 파라미터의 0이 아닌 값 및 대기열의 URL을 포함하여 대기열의 속성을 설정하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `setQueueAttributes` 메서드를 호출합니다. 그러면 대기열에 대해 긴 폴링이 활성화됩니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  Attributes: {
    ReceiveMessageWaitTimeSeconds: "20",
  },
  QueueUrl: "SQS_QUEUE_URL",
};

sqs.setQueueAttributes(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_longpolling_existingqueue.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_longpolling_existingqueue.js)에서 찾을 수 있습니다.

## 메시지 수신 시 긴 폴링 활성화
<a name="sqs-examples-enable-long-polling-on-receive-message"></a>

파일 이름이 `sqs_longpolling_receivemessage.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon Simple Queue Service에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. `WaitTimeSeconds` 파라미터의 0이 아닌 값 및 대기열의 URL을 포함하여 메시지를 수신하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. `receiveMessage` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var queueURL = "SQS_QUEUE_URL";

var params = {
  AttributeNames: ["SentTimestamp"],
  MaxNumberOfMessages: 1,
  MessageAttributeNames: ["All"],
  QueueUrl: queueURL,
  WaitTimeSeconds: 20,
};

sqs.receiveMessage(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_longpolling_receivemessage.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_longpolling_receivemessage.js)에서 찾을 수 있습니다.

# Amazon SQS에서 DLQ(Dead Letter Queue) 사용
<a name="sqs-examples-dead-letter-queues"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ 대기열이 처리할 수 없는 다른 대기열의 메시지를 수신하고 보관하기 위해 대기열을 사용하는 방법

## 시나리오
<a name="sqs-examples-dead-letter-queues-scenario"></a>

배달 못한 편지 대기열은 성공적으로 처리하지 못한 메시지를 다른 (소스) 대기열에서 보낼 수 있는 대기열입니다. 배달 못한 편지 대기열에서 이 메시지를 구분하고 격리하여 처리에 실패한 이유를 확인할 수 있습니다. 배달 못한 편지 대기열로 메시지를 보내는 각 소스 대기열을 개별적으로 구성해야 합니다. 여러 대기열은 단일 배달 못한 편지 대기열을 대상으로 삼을 수 있습니다.

이 예제에서는 Node.js 모듈을 사용하여 배달 못한 편지 대기열로 메시지를 라우팅합니다. Node.js 모듈은 SDK for JavaScript로 `AWS.SQS` 클라이언트 클래스의 다음 메서드를 사용하여 DLQ(Dead Letter Queue)를 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#setQueueAttributes-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#setQueueAttributes-property)

Amazon SQS DLQ(Dead Letter Queue)에 대한 자세한 내용은 *Amazon Simple Queue Service 개발자 안내서*의 [Amazon SQS DLQ(Dead Letter Queue) 사용](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)을 참조하세요.

## 사전 필수 작업
<a name="sqs-examples-dead-letter-queues-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ Node.js를 설치합니다. Node.js 설치에 대한 자세한 내용은 [Node.js 웹 사이트](https://nodejs.org)를 참조하세요.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 자격 증명 파일 제공에 대한 자세한 내용은 [공유 인증 자격 증명 파일에서 Node.js에 인증 자격 증명 로드](loading-node-credentials-shared.md) 섹션을 참조하세요.
+ DLQ(Dead Letter Queue)로 제공할 Amazon SQS 대기열을 생성합니다. 대기열 생성에 대한 예제는 [Amazon SQS에서 대기열 사용](sqs-examples-using-queues.md) 섹션을 참조하세요.

## 소스 대기열 구성
<a name="sqs-examples-dead-letter-queues-configuring-source-queues"></a>

배달 못한 편지 대기열 역할을 하는 대기열을 생성한 후에는 다른 대기열이 처리되지 못한 메시지를 배달 못한 편지 대기열로 라우팅하도록 구성해야 합니다. 이렇게 하려면 배달 못한 편지 대기열로 사용할 대기열을 식별하는 리드라이브 정책을 지정하고 개별 메시지가 배달 못한 편지 대기열로 라우팅되기 전 최대 수신 수를 설정해야 합니다.

파일 이름이 `sqs_deadletterqueue.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성해야 합니다. Amazon SQS에 액세스하려면 `AWS.SQS` 서비스 객체를 생성합니다. 배달 못한 편지 대기열의 ARN과 `maxReceiveCount`의 값을 모두 지정하는 `RedrivePolicy` 파라미터를 포함하여 대기열 속성을 업데이트하는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 또한 구성하고자 하는 URL 소스 대기열을 지정합니다. `setQueueAttributes` 메서드를 호출합니다.

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  Attributes: {
    RedrivePolicy:
      '{"deadLetterTargetArn":"DEAD_LETTER_QUEUE_ARN","maxReceiveCount":"10"}',
  },
  QueueUrl: "SOURCE_QUEUE_URL",
};

sqs.setQueueAttributes(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

예제를 실행하려면 명령줄에서 다음을 입력합니다.

```
node sqs_deadletterqueue.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascript/example_code/sqs/sqs_deadletterqueue.js)에서 찾을 수 있습니다.