

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (V3) 的所有 API 操作。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 適用於 JavaScript 的 SDK 程式碼範例
<a name="sdk-code-samples"></a>

本節中的主題包含如何使用 適用於 JavaScript 的 AWS SDK 搭配各種 服務的 APIs 來執行常見任務的範例。

在 [AWS GitHub 上的程式碼範例儲存庫中尋找這些範例和其他範例的原始程式碼](https://github.com/awsdocs/aws-doc-sdk-examples)。若要提議新的程式碼範例，讓 AWS 文件團隊考慮生產，請建立 請求。該團隊想要產生比僅涵蓋個別 API 呼叫之簡易程式碼更為廣泛的程式碼範例，以涵蓋更為廣泛的案例和使用案例。如需說明，請參閱 [ GitHub 上貢獻準則](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/CONTRIBUTING.md)中的*編寫程式碼*一節。

**重要**  
這些範例使用 ECMAScript6 匯入/匯出語法。  
這需要 Node.js 14.17 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md) 以取得轉換準則。

**Topics**
+ [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)
+ [AWS Elemental MediaConvert 範例](emc-examples.md)
+ [AWS Lambda 範例](lambda-examples.md)
+ [Amazon Lex 範例](lex-examples.md)
+ [Amazon Polly 範例](polly-examples.md)
+ [Amazon Redshift 範例](redshift-examples.md)
+ [Amazon Simple Email Service 範例](ses-examples.md)
+ [Amazon Simple Notification Service 範例](sns-examples.md)
+ [Amazon Transcribe 範例](Transcribe-examples.md)
+ [在 Amazon EC2 執行個體上設定 Node.js](setting-up-node-on-ec2-instance.md)
+ [使用 API Gateway 叫用 Lambda](api-gateway-invoking-lambda-example.md)
+ [建立排程事件以執行 AWS Lambda 函數](scheduled-events-invoking-lambda-example.md)
+ [建置 Amazon Lex 聊天機器人](lex-bot-example.md)

# JavaScript ES6/CommonJS 語法
<a name="sdk-example-javascript-syntax"></a>

 適用於 JavaScript 的 AWS SDK 程式碼範例以 ECMAScript 6 (ES6) 撰寫。ES6 帶來新的語法和新功能，讓您的程式碼更現代化、更易讀，並執行更多操作。

ES6 要求您使用 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)不過，如果您願意，您可以使用下列準則將我們的任何範例轉換為 CommonJS 語法：
+ `"type" : "module"` 從專案環境中`package.json`的 移除 。
+ 將所有 ES6 `import`陳述式轉換為 CommonJS `require`陳述式。例如，轉換：

  ```
  import { CreateBucketCommand } from "@aws-sdk/client-s3";
  import { s3 } from "./libs/s3Client.js";
  ```

  至其 CommonJS 對等項目：

  ```
  const { CreateBucketCommand } = require("@aws-sdk/client-s3");
  const { s3 } = require("./libs/s3Client.js");
  ```
+ 將所有 ES6 `export`陳述式轉換為 CommonJS `module.exports`陳述式。例如，轉換：

  ```
  export {s3}
  ```

  至其 CommonJS 對等項目：

  ```
  module.exports = {s3}
  ```

下列範例示範在 ES6 和 CommonJS 中建立 Amazon S3 儲存貯體的程式碼範例。

------
#### [ ES6 ]

libs/s3Client.js

```
// Create service client module using ES6 syntax.
import { S3Client } from "@aws-sdk/client-s3";
// Set the AWS region
const REGION = "eu-west-1"; //e.g. "us-east-1"
// Create Amazon S3 service object.
const s3 = new S3Client({ region: REGION });
// Export 's3' constant.
export {s3};
```

s3\$1createbucket.js

```
// Get service clients module and commands using ES6 syntax.
 import { CreateBucketCommand } from "@aws-sdk/client-s3";
 import { s3 } from "./libs/s3Client.js";

// Get service clients module and commands using CommonJS syntax.
// const { CreateBucketCommand } = require("@aws-sdk/client-s3");
// const { s3 } = require("./libs/s3Client.js");

// Set the bucket parameters
const bucketParams = { Bucket: "BUCKET_NAME" };

// Create the Amazon S3 bucket.
const run = async () => {
  try {
    const data = await s3.send(new CreateBucketCommand(bucketParams));
    console.log("Success", data.Location);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------
#### [ CommonJS ]

libs/s3Client.js

```
// Create service client module using CommonJS syntax.
 const { S3Client } = require("@aws-sdk/client-s3");
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
 // Create Amazon S3 service object.
const s3 = new S3Client({ region: REGION });
// Export 's3' constant.
 module.exports ={s3};
```

s3\$1createbucket.js

```
// Get service clients module and commands using CommonJS syntax.
const { CreateBucketCommand } = require("@aws-sdk/client-s3");
const { s3 } = require("./libs/s3Client.js");

// Set the bucket parameters
const bucketParams = { Bucket: "BUCKET_NAME" };

// Create the Amazon S3 bucket.
const run = async () => {
  try {
    const data = await s3.send(new CreateBucketCommand(bucketParams));
    console.log("Success", data.Location);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------

# AWS Elemental MediaConvert 範例
<a name="emc-examples"></a>

AWS Elemental MediaConvert 是以檔案為基礎的視訊轉碼服務，具有廣播級功能。您可以將其用於建立跨網際網路的廣播資產及隨選視訊 (VOD) 交付資產。如需詳細資訊，請參閱[「*AWS Elemental MediaConvert 使用者指南」*](https://docs.aws.amazon.com/mediaconvert/latest/ug/)。

MediaConvert 的 JavaScript API 透過`MediaConvert`用戶端類別公開。如需詳細資訊，請參閱 API 參考中的[類別：MediaConvert](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/)。

**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/zh_tw/sdk-for-javascript/v3/developer-guide/images/nodeicon.png)

**這個 Node.js 程式碼範例會說明：**
+ 如何在 MediaConvert 中建立轉碼任務。
+ 如何取消轉碼任務。
+ 如何擷取已完成轉碼任務的 JSON。
+ 如何擷取高達 20 個最近建立任務的 JSON 陣列。

## 案例
<a name="emc-examples-jobs-scenario"></a>

在此範例中，您使用 Node.js 模組呼叫 MediaConvert 來建立和管理轉碼任務。此程式碼使用以下 MediaConvert 用戶端類別的方法，使用適用於 JavaScript 的 SDK 來執行此操作：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CancelJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CancelJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/GetJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/GetJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobsCommand/)

## 先決條件任務
<a name="emc-examples-jobs-prerequisites"></a>

若要設定和執行此範例，請先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/mediaconvert/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。
+ 建立和設定 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)。
+ 建立 IAM 角色，讓 MediaConvert 存取您的輸入檔案，以及儲存輸出檔案的 Amazon S3 儲存貯體。如需詳細資訊，請參閱[《 使用者指南》中的設定 IAM 許可](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html)。 *AWS Elemental MediaConvert *

**重要**  
此範例使用 ECMAScript6 (ES6)。這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)  
不過，如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 定義簡單的轉碼任務
<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。

**注意**  
將 *JOB\$1QUEUE\$1ARN* 取代為 MediaConvert 任務佇列、將 *IAM\$1ROLE\$1ARN* 取代為 IAM 角色的 Amazon Resource Name (ARN)、將 *OUTPUT\$1BUCKET\$1NAME* 取代為目的地儲存貯體名稱 - 例如 "s3：//OUTPUT\$1BUCKET\$1NAME/"，以及將 *INPUT\$1BUCKET\$1AND\$1FILENAME* 取代為輸入儲存貯體和檔案名稱 - 例如 "s3：/INPUT\$1BUCKET/FILE\$1NAME"。

```
const params = {
  Queue: "JOB_QUEUE_ARN", //JOB_QUEUE_ARN
  UserMetadata: {
    Customer: "Amazon",
  },
  Role: "IAM_ROLE_ARN", //IAM_ROLE_ARN
  Settings: {
    OutputGroups: [
      {
        Name: "File Group",
        OutputGroupSettings: {
          Type: "FILE_GROUP_SETTINGS",
          FileGroupSettings: {
            Destination: "OUTPUT_BUCKET_NAME", //OUTPUT_BUCKET_NAME, e.g., "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",
        FileInput: "INPUT_BUCKET_AND_FILENAME", //INPUT_BUCKET_AND_FILENAME, e.g., "s3://BUCKET_NAME/FILE_NAME"
      },
    ],
    TimecodeConfig: {
      Source: "EMBEDDED",
    },
  },
};
```

## 建立轉碼任務
<a name="emc-examples-jobs-create"></a>

建立任務參數 JSON 之後，請呼叫非同步`run`方法來叫用`MediaConvert`用戶端服務物件，並傳遞參數。回應 `data` 中會傳回所建立任務的 ID。

```
const run = async () => {
  try {
    const data = await emcClient.send(new CreateJobCommand(params));
    console.log("Job created!", data);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node emc_createjob.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_createjob.js)此完整範例程式碼。

## 取消轉碼任務
<a name="emc-examples-jobs-cancel"></a>

以檔名 `emc_canceljob.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括下載所需的用戶端和套件。建立包含要取消任務 ID 的 JSON。然後，透過建立叫用`MediaConvert`用戶端服務物件、傳遞參數的承諾來呼叫 `CancelJobCommand`方法。在 promise 回呼中處理回應。

**注意**  
將 *JOB\$1ID* 取代為要取消的任務 ID。

```
// Import required AWS-SDK clients and commands for Node.js
import { CancelJobCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

// Set the parameters
const params = { Id: "JOB_ID" }; //JOB_ID

const run = async () => {
  try {
    const data = await emcClient.send(new CancelJobCommand(params));
    console.log(`Job  ${params.Id} is canceled`);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node ec2_canceljob.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_canceljob.js)此範例程式碼。

## 列出最近的轉碼任務
<a name="emc-examples-jobs-listing"></a>

以檔名 `emc_listjobs.js` 建立一個 Node.js 模組。請務必如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立參數 JSON，包括指定要以 `ASCENDING`或 `DESCENDING`順序排序清單的值、要檢查之任務佇列的 Amazon Resource Name (ARN)，以及要包含的任務狀態。然後，透過建立叫用`MediaConvert`用戶端服務物件並傳遞參數的承諾來呼叫 `ListJobsCommand`方法。

**注意**  
將 *QUEUE\$1ARN* 取代為要檢查之任務佇列的 Amazon Resource Name (ARN)，並將 *STATUS* 取代為佇列的狀態。

```
// Import required AWS-SDK clients and commands for Node.js
import { ListJobsCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

// Set the parameters
const params = {
  MaxResults: 10,
  Order: "ASCENDING",
  Queue: "QUEUE_ARN",
  Status: "SUBMITTED", // e.g., "SUBMITTED"
};

const run = async () => {
  try {
    const data = await emcClient.send(new ListJobsCommand(params));
    console.log("Success. Jobs: ", data.Jobs);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node emc_listjobs.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_listjobs.js)此範例程式碼。

# 在 MediaConvert 中使用任務範本
<a name="emc-examples-templates"></a>

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

**這個 Node.js 程式碼範例會說明：**
+ 如何建立 AWS Elemental MediaConvert 任務範本。
+ 如何使用任務範本來建立轉譯任務。
+ 如何列出所有任務範本。
+ 如何刪除任務範本。

## 案例
<a name="emc-examples-templates-scenario"></a>

在 MediaConvert 中建立轉碼任務所需的 JSON 是詳細的，其中包含大量的設定。您可以在您在建立後續任務能用的任務範本中儲存已知良好的設定，來大幅簡化任務的建立作業。在此範例中，您使用 Node.js 模組呼叫 MediaConvert 來建立、使用和管理任務範本。此程式碼使用以下 MediaConvert 用戶端類別的方法，使用適用於 JavaScript 的 SDK 來執行此操作：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/DeleteJobTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/DeleteJobTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobTemplatesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobTemplatesCommand/)

## 先決條件任務
<a name="emc-example-templates-prerequisites"></a>

若要設定和執行此範例，請先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/mediaconvert/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。
+ 建立 IAM 角色，讓 MediaConvert 存取您的輸入檔案，以及儲存輸出檔案的 Amazon S3 儲存貯體。如需詳細資訊，請參閱[《 使用者指南》中的設定 IAM 許可](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.html)。 *AWS Elemental MediaConvert *

**重要**  
這些範例使用 ECMAScript6 (ES6)。這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)  
不過，如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 建立任務範本
<a name="emc-examples-templates-create"></a>

以檔名 `emc_create_jobtemplate.js` 建立一個 Node.js 模組。請務必如先前所示設定 SDK，包括安裝所需的用戶端和套件。

為範本建立指定 JSON 參數。您可以使用來自先前成功任務的多數 JSON 參數，來在範本中指定 `Settings` 值。此範例使用來自 [在 MediaConvert 中建立和管理轉碼任務](emc-examples-jobs.md)的任務設定。

透過建立叫用`MediaConvert`用戶端服務物件並傳遞參數的承諾來呼叫 `CreateJobTemplateCommand`方法。

**注意**  
將 *JOB\$1QUEUE\$1ARN* 取代為要檢查之任務佇列的 Amazon Resource Name (ARN)，並將 *BUCKET\$1NAME* 取代為目的地 Amazon S3 儲存貯體的名稱，例如 "s3：//BUCKET\$1NAME/"。

```
// Import required AWS-SDK clients and commands for Node.js
import { CreateJobTemplateCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

const params = {
  Category: "YouTube Jobs",
  Description: "Final production transcode",
  Name: "DemoTemplate",
  Queue: "JOB_QUEUE_ARN", //JOB_QUEUE_ARN
  Settings: {
    OutputGroups: [
      {
        Name: "File Group",
        OutputGroupSettings: {
          Type: "FILE_GROUP_SETTINGS",
          FileGroupSettings: {
            Destination: "BUCKET_NAME", // BUCKET_NAME e.g., "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",
    },
  },
};

const run = async () => {
  try {
    // Create a promise on a MediaConvert object
    const data = await emcClient.send(new CreateJobTemplateCommand(params));
    console.log("Success!", data);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node emc_create_jobtemplate.js 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_create_jobtemplate.js)範例程式碼。

## 從任務範本建立轉碼任務
<a name="emc-examples-templates-createjob"></a>

以檔名 `emc_template_createjob.js` 建立一個 Node.js 模組。請務必如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立任務建立參數 JSON，其中包含要用的任務範本名稱，以及專屬於您在建立之任務的要使用 `Settings`。然後，透過建立叫用`MediaConvert`用戶端服務物件、傳遞參數的承諾來呼叫 `CreateJobsCommand`方法。

**注意**  
將 *JOB\$1QUEUE\$1ARN* 取代為任務佇列的 Amazon Resource Name (ARN)，將 *KEY\$1PAIR\$1NAME* 取代為 *TEMPLATE\$1NAME* 取代為 ，將 *ROLE\$1ARN* 取代為角色的 Amazon Resource Name (ARN)，並將 * INPUT\$1BUCKET\$1AND\$1FILENAME* 取代為輸入儲存貯體和檔案名稱 - 例如 "s3：//BUCKET\$1NAME/FILE\$1NAME"。

```
// Import required AWS-SDK clients and commands for Node.js
import { CreateJobCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

const params = {
  Queue: "QUEUE_ARN", //QUEUE_ARN
  JobTemplate: "TEMPLATE_NAME", //TEMPLATE_NAME
  Role: "ROLE_ARN", //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: "INPUT_BUCKET_AND_FILENAME", //INPUT_BUCKET_AND_FILENAME, e.g., "s3://BUCKET_NAME/FILE_NAME"
      },
    ],
  },
};

const run = async () => {
  try {
    const data = await emcClient.send(new CreateJobCommand(params));
    console.log("Success! ", data);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node emc_template_createjob.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_template_createjob.js)此範例程式碼。

## 列出您的任務範本
<a name="emc-examples-templates-listing"></a>

以檔名 `emc_listtemplates.js` 建立一個 Node.js 模組。請務必如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件，傳遞 `MediaConvert` 用戶端類別的 `listTemplates` 方法的空請求參數。包含值來判斷要列出哪些範本 (`NAME`, `CREATION DATE`, `SYSTEM`)、要列出多少以及這些範本的排序。若要呼叫 `ListTemplatesCommand`方法，請建立叫用 MediaConvert 用戶端服務物件並傳遞參數的承諾。

```
// Import required AWS-SDK clients and commands for Node.js
import { ListJobTemplatesCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

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

const run = async () => {
  try {
    const data = await emcClient.send(new ListJobTemplatesCommand(params));
    console.log("Success ", data.JobTemplates);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node emc_listtemplates.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_template_createjob.js)此範例程式碼。

## 刪除任務範本
<a name="emc-examples-templates-delete"></a>

以檔名 `emc_deletetemplate.js` 建立一個 Node.js 模組。請務必如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件，為 `MediaConvert` 用戶端類別的 `DeleteJobTemplateCommand` 方法傳遞您要刪除做為參數的任務範本名稱。若要呼叫 `DeleteJobTemplateCommand`方法，請建立叫用 MediaConvert 用戶端服務物件並傳遞參數的承諾。

```
// Import required AWS-SDK clients and commands for Node.js
import { DeleteJobTemplateCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

// Set the parameters
const params = { Name: "test" }; //TEMPLATE_NAME

const run = async () => {
  try {
    const data = await emcClient.send(new DeleteJobTemplateCommand(params));
    console.log(
      "Success, template deleted! Request ID:",
      data.$metadata.requestId,
    );
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node emc_deletetemplate.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_deletetemplate.js)此範例程式碼。

# AWS Lambda 範例
<a name="lambda-examples"></a>

AWS Lambda 是一種無伺服器運算服務，可讓您執行程式碼，而無需佈建或管理伺服器、建立工作負載感知叢集擴展邏輯、維護事件整合，或管理執行時間。

的 JavaScript API 透過 [LambdaService](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-lambda/) 用戶端類別 AWS Lambda 公開。

以下是示範如何建立 Lambda 函數並將其與 適用於 JavaScript 的 AWS SDK v3 搭配使用的範例清單：
+ [使用 API Gateway 叫用 Lambda](api-gateway-invoking-lambda-example.md)
+ [建立排程事件以執行 AWS Lambda 函數](scheduled-events-invoking-lambda-example.md)

# Amazon Lex 範例
<a name="lex-examples"></a>

Amazon Lex 是一種 AWS 服務，可使用語音和文字將對話界面建置到應用程式中。

Amazon Lex 的 JavaScript API 透過 [Lex 執行期服務](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-lex-runtime-service/)用戶端類別公開。
+ [建置 Amazon Lex 聊天機器人](lex-bot-example.md)

# Amazon Polly 範例
<a name="polly-examples"></a>

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

**這個 Node.js 程式碼範例會說明：**
+ 使用 Amazon Polly 將錄製的音訊上傳至 Amazon S3

## 案例
<a name="polly-example-synthesize-to-s3-scenario"></a>

在此範例中，一系列 Node.js 模組用於使用以下 Amazon S3 用戶端類別的方法，使用 Amazon Polly 自動將錄製的音訊上傳至 Amazon S3：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-polly/Class/StartSpeechSynthesisTaskCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-polly/Class/StartSpeechSynthesisTaskCommand/)

## 先決條件任務
<a name="polly-example-synthesize-to-s3-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 依照[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/s3/README.md) 上的指示，設定專案環境以執行節點 JavaScript 範例。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。
+ 建立 AWS Identity and Access Management (IAM) 未驗證的 Amazon Cognito 使用者角色輪詢：SynthesizeSpeech 許可，以及連接 IAM 角色的 Amazon Cognito 身分集區。以下[使用 建立 AWS 資源 CloudFormation](#polly-example-synthesize-to-s3-create-resources)章節說明如何建立這些資源。

**注意**  
此範例使用 Amazon Cognito，但如果您沒有使用 Amazon Cognito，您的 AWS 使用者必須擁有下列 IAM 許可政策  

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "mobileanalytics:PutEvents",
        "cognito-sync:*"
      ],
      "Resource": "*",
      "Effect": "Allow"
    },
    {
      "Action": "polly:SynthesizeSpeech",
      "Resource": "*",
      "Effect": "Allow"
    }
  ]
}
```

## 使用 建立 AWS 資源 CloudFormation
<a name="polly-example-synthesize-to-s3-create-resources"></a>

CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署。如需 的詳細資訊 CloudFormation，請參閱[AWS CloudFormation 《 使用者指南》](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)。

若要建立 CloudFormation 堆疊：

1. 在 [AWS CLI 使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)中安裝和設定 AWS CLI 下列指示。

1. 在專案資料夾的`setup.yaml`根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/polly/general-examples/src/setup.yaml)內容複製到其中。
**注意**  
 CloudFormation 範本是使用 [ GitHub 上此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/resources/cdk/javascript_example_code_polly_aws_service/)提供的 AWS CDK 產生。如需 的詳細資訊 AWS CDK，請參閱 [AWS Cloud Development Kit (AWS CDK) 開發人員指南](https://docs.aws.amazon.com/cdk/latest/guide/)。

1. 從命令列執行下列命令，將 *STACK\$1NAME* 取代為堆疊的唯一名稱。
**重要**  
堆疊名稱在 AWS 區域和 AWS 帳戶中必須是唯一的。您最多可以指定 128 個字元，且允許使用數字和連字號。

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   如需`create-stack`命令參數的詳細資訊，請參閱 [AWS CLI 命令參考指南](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html)和 [CloudFormation 使用者指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)。

1. 導覽至 CloudFormation 管理主控台，選擇 **Stacks**，選擇堆疊名稱，然後選擇**資源**索引標籤以檢視建立的資源清單。  
![\[CloudFormation 資源\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/cfn_polly.png)

## 使用 Amazon Polly 將錄製的音訊上傳至 Amazon S3
<a name="polly-example-synthesize-to-s3-example"></a>

以檔名 `polly_synthesize_to_s3.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。在程式碼中，輸入 *REGION* 和 *BUCKET\$1NAME*。若要存取 Amazon Polly，請建立`Polly`用戶端服務物件。`IdentityPoolId` 將 *"IDENTITY\$1POOL\$1ID"* 取代為您為此範例建立的 Amazon Cognito 身分集區**範例頁面**中的 。這也會傳遞給每個用戶端物件。

呼叫 Amazon Polly 用戶端服務物件的 `StartSpeechSynthesisCommand`方法合成語音訊息，並將其上傳至 Amazon S3 儲存貯體。

```
import { StartSpeechSynthesisTaskCommand } from "@aws-sdk/client-polly";
import { pollyClient } from "./libs/pollyClient.js";

// Create the parameters
const params = {
  OutputFormat: "mp3",
  OutputS3BucketName: "videoanalyzerbucket",
  Text: "Hello David, How are you?",
  TextType: "text",
  VoiceId: "Joanna",
  SampleRate: "22050",
};

const run = async () => {
  try {
    await pollyClient.send(new StartSpeechSynthesisTaskCommand(params));
    console.log(`Success, audio file added to ${params.OutputS3BucketName}`);
  } catch (err) {
    console.log("Error putting object", err);
  }
};
run();
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/polly/general-examples/src/polly_synthesize_to_s3.js)找到這個範本程式碼。

# Amazon Redshift 範例
<a name="redshift-examples"></a>

Amazon Redshift 是一種在雲端中完全受管的 PB 級資料倉儲服務。Amazon Redshift 資料倉儲是稱為節點**的運算資源的集合，組織成稱為叢集**的群組。每個叢集皆執行 Amazon Redshift 引擎並包含一或多個資料庫。

![\[JavaScript 環境、軟體開發套件和 Amazon Redshift 之間的關係\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/code-samples-redshift.png)


Amazon Redshift 的 JavaScript API 透過 [Amazon Redshift](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/Redshift/) 用戶端類別公開。

**Topics**
+ [Amazon Redshift 範例](redshift-examples-section.md)

# Amazon Redshift 範例
<a name="redshift-examples-section"></a>

在此範例中，一系列 Node.js 模組用於建立、修改、描述 的參數，然後使用下列 `Redshift`用戶端類別方法刪除 Amazon Redshift 叢集：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/CreateClusterCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/CreateClusterCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/ModifyClusterCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/ModifyClusterCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DescribeClustersCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DescribeClustersCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DeleteClusterCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DeleteClusterCommand/)

如需 Amazon Redshift 使用者的詳細資訊，請參閱 [Amazon Redshift 入門指南](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html)。

## 先決條件任務
<a name="s3-example-configuring-buckets-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/redshift/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)

## 建立 Amazon Redshift 叢集
<a name="redshift-create-cluster"></a>

此範例示範如何使用 建立 Amazon Redshift 叢集 適用於 JavaScript 的 AWS SDK。如需詳細資訊，請參閱 [CreateCluster](https://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateCluster)。

**重要**  
*您即將建立的叢集是即時的 （而不是在沙盒中執行）。您需要支付叢集的標準 Amazon Redshift 使用費，直到刪除叢集為止。如果您在建立叢集時以相同的坐姿刪除叢集，則總費用最少。 *

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`redshiftClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Redshift 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/libs/redshiftClient.js)範例程式碼。

以檔名 `redshift-create-cluster.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。建立參數物件，指定要佈建的節點類型，以及在叢集中自動建立的資料庫執行個體主登入憑證，最後是叢集類型。

**注意**  
將 *CLUSTER\$1NAME* 取代為叢集的名稱。對於 *NODE\$1TYPE*，指定要佈建的節點類型，例如 'dc2.large'。*MASTER\$1USERNAME* 和 *MASTER\$1USER\$1PASSWORD* 是叢集中資料庫執行個體主要使用者的登入憑證。針對 *CLUSTER\$1TYPE*，輸入叢集的類型。如果您指定 `single-node`，則不需要 `NumberOfNodes` 參數。其餘參數為選用。

```
// Import required AWS SDK clients and commands for Node.js
import { CreateClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME", // Required
  NodeType: "NODE_TYPE", //Required
  MasterUsername: "MASTER_USER_NAME", // Required - must be lowercase
  MasterUserPassword: "MASTER_USER_PASSWORD", // Required - must contain at least one uppercase letter, and one number
  ClusterType: "CLUSTER_TYPE", // Required
  IAMRoleARN: "IAM_ROLE_ARN", // Optional - the ARN of an IAM role with permissions your cluster needs to access other AWS services on your behalf, such as Amazon S3.
  ClusterSubnetGroupName: "CLUSTER_SUBNET_GROUPNAME", //Optional - the name of a cluster subnet group to be associated with this cluster. Defaults to 'default' if not specified.
  DBName: "DATABASE_NAME", // Optional - defaults to 'dev' if not specified
  Port: "PORT_NUMBER", // Optional - defaults to '5439' if not specified
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new CreateClusterCommand(params));
    console.log(
      `Cluster ${data.Cluster.ClusterIdentifier} successfully created`,
    );
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node redshift-create-cluster.js  
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-create-cluster.js)找到這個範本程式碼。

## 修改 Amazon Redshift 叢集
<a name="redshift-modify-cluster"></a>

此範例說明如何使用 修改 Amazon Redshift 叢集的主要使用者密碼 適用於 JavaScript 的 AWS SDK。如需您可以修改哪些其他設定的詳細資訊，請參閱 [ModifyCluster](https://docs.aws.amazon.com/redshift/latest/APIReference/API_ModifyCluster.html)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`redshiftClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Redshift 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/libs/redshiftClient.js)範例程式碼。

以檔名 `redshift-modify-cluster.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。指定 AWS 區域、您要修改的叢集名稱，以及新的主要使用者密碼。

**注意**  
將 *CLUSTER\$1NAME* 取代為叢集的名稱，並將 *MASTER\$1USER\$1PASSWORD* 取代為新的主要使用者密碼。

```
// Import required AWS SDK clients and commands for Node.js
import { ModifyClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

// Set the parameters
const params = {
  ClusterIdentifier: "CLUSTER_NAME",
  MasterUserPassword: "NEW_MASTER_USER_PASSWORD",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new ModifyClusterCommand(params));
    console.log("Success was modified.", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node redshift-modify-cluster.js 
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-modify-cluster.js)找到這個範本程式碼。

## 檢視 Amazon Redshift 叢集的詳細資訊
<a name="redshift-describe-cluster"></a>

此範例說明如何使用 檢視 Amazon Redshift 叢集的詳細資訊 適用於 JavaScript 的 AWS SDK。如需選用的詳細資訊，請參閱 [DescribeClusters](https://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusters.html)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`redshiftClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Redshift 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/libs/redshiftClient.js)範例程式碼。

以檔名 `redshift-describe-clusters.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。指定 AWS 區域、您要修改的叢集名稱，以及新的主要使用者密碼。

**注意**  
將 *CLUSTER\$1NAME* 取代為叢集的名稱。

```
// Import required AWS SDK clients and commands for Node.js
import { DescribeClustersCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new DescribeClustersCommand(params));
    console.log("Success", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node redshift-describe-clusters.js 
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-describe-clusters.js)找到這個範本程式碼。

## 刪除 Amazon Redshift 叢集
<a name="redshift-delete-cluster"></a>

此範例說明如何使用 檢視 Amazon Redshift 叢集的詳細資訊 適用於 JavaScript 的 AWS SDK。如需您可以修改哪些其他設定的詳細資訊，請參閱 [DeleteCluster](https://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteCluster.html)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`redshiftClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Redshift 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/libs/redshiftClient.js)範例程式碼。

使用名為 的檔案建立 Node.js 模組`redshift-delete-clusters.js`。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。指定 AWS 區域、您要修改的叢集名稱，以及新的主要使用者密碼。指定是否要在刪除之前儲存叢集的最終快照，如果是，則指定快照的 ID。

**注意**  
將 *CLUSTER\$1NAME* 取代為叢集的名稱。對於 *SkipFinalClusterSnapshot*，指定是否在刪除叢集之前建立叢集的最終快照。如果您指定 'false'，請在 *CLUSTER\$1SNAPSHOT\$1ID* 中指定最終叢集快照的 ID。您可以按一下**叢集**儀表板上叢集**快照**欄中的連結，然後向下捲動至**快照**窗格，以取得此 ID。請注意， 桿`rs:`不屬於快照 ID。

```
// Import required AWS SDK clients and commands for Node.js
import { DeleteClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME",
  SkipFinalClusterSnapshot: false,
  FinalClusterSnapshotIdentifier: "CLUSTER_SNAPSHOT_ID",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new DeleteClusterCommand(params));
    console.log("Success, cluster deleted. ", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node redshift-delete-cluster.js  
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-delete-cluster.js)找到這個範本程式碼。

# Amazon Simple Email Service 範例
<a name="ses-examples"></a>

Amazon Simple Email Service (Amazon SES) 是一種雲端電子郵件傳送服務，旨在協助數位行銷人員和應用程式開發人員傳送行銷、通知和交易電子郵件。這是一個可靠且經濟實惠的服務，適合透過電子郵件與客戶保持聯繫的所有規模公司使用。

![\[JavaScript 環境、軟體開發套件和 Amazon SES 之間的關係\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/code-samples-ses.png)


Amazon SES 的 JavaScript API 透過`SES`用戶端類別公開。如需使用 Amazon SES 用戶端類別的詳細資訊，請參閱 API 參考中的[類別：SES](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SES/)。

**Topics**
+ [管理 Amazon SES 身分](ses-examples-managing-identities.md)
+ [在 Amazon SES 中使用電子郵件範本](ses-examples-creating-template.md)
+ [使用 Amazon SES 傳送電子郵件](ses-examples-sending-email.md)

# 管理 Amazon SES 身分
<a name="ses-examples-managing-identities"></a>

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

**這個 Node.js 程式碼範例會說明：**
+ 如何驗證與 Amazon SES 搭配使用的電子郵件地址和網域。
+ 如何將 AWS Identity and Access Management (IAM) 政策指派給您的 Amazon SES 身分。
+ 如何列出您 AWS 帳戶的所有 Amazon SES 身分。
+ 如何刪除與 Amazon SES 搭配使用的身分。

Amazon SES *身分*是 Amazon SES 用來傳送電子郵件的電子郵件地址或網域。Amazon SES 要求您驗證電子郵件身分，確認您擁有這些身分，並防止其他人使用這些身分。

如需如何在 Amazon SES 中驗證電子郵件地址和網域的詳細資訊，請參閱《Amazon Simple Email Service [開發人員指南》中的在 Amazon SES 中驗證電子郵件地址和網域](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 模組使用以下`SES`用戶端類別的方法，使用適用於 JavaScript 的 SDK 來驗證電子郵件地址和網域：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListIdentitiesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListIdentitiesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteIdentityCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteIdentityCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyEmailIdentityCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyEmailIdentityCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyDomainIdentityCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyDomainIdentityCommand/)

## 先決條件任務
<a name="ses-examples-verifying-identities-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 列出您的身分
<a name="ses-examples-listing-identities"></a>

在此範例中，使用 Node.js 模組列出要與 Amazon SES 搭配使用的電子郵件地址和網域。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_listidentities.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件，以傳遞 `SES` 用戶端類別的 `ListIdentitiesCommand` 方法之 `IdentityType` 和其他參數。若要呼叫 `ListIdentitiesCommand`方法，請叫用 Amazon SES 服務物件，傳遞參數物件。

 `data` 傳回的 包含 `IdentityType` 參數指定的網域身分陣列。

**注意**  
將 *IdentityType* 取代為身分類型，可以是 "EmailAddress" 或 "Domain"。

```
import { ListIdentitiesCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createListIdentitiesCommand = () =>
  new ListIdentitiesCommand({ IdentityType: "EmailAddress", MaxItems: 10 });

const run = async () => {
  const listIdentitiesCommand = createListIdentitiesCommand();

  try {
    return await sesClient.send(listIdentitiesCommand);
  } catch (err) {
    console.log("Failed to list identities.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node ses_listidentities.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_listidentities.js)此範例程式碼。

## 驗證電子郵件地址身分
<a name="ses-examples-verifying-email"></a>

在此範例中，使用 Node.js 模組來驗證要與 Amazon SES 搭配使用的電子郵件寄件者。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_verifyemailidentity.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括下載所需的用戶端和套件。

建立物件以傳遞 `SES` 用戶端類別的 `VerifyEmailIdentityCommand` 方法之 `EmailAddress` 參數。若要呼叫 `VerifyEmailIdentityCommand`方法，請叫用 Amazon SES 用戶端服務物件，傳遞參數。

**注意**  
將 *EMAIL\$1ADDRESS* 取代為電子郵件地址，例如 name@example.com。

```
// Import required AWS SDK clients and commands for Node.js
import { VerifyEmailIdentityCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const EMAIL_ADDRESS = "name@example.com";

const createVerifyEmailIdentityCommand = (emailAddress) => {
  return new VerifyEmailIdentityCommand({ EmailAddress: emailAddress });
};

const run = async () => {
  const verifyEmailIdentityCommand =
    createVerifyEmailIdentityCommand(EMAIL_ADDRESS);
  try {
    return await sesClient.send(verifyEmailIdentityCommand);
  } catch (err) {
    console.log("Failed to verify email identity.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。網域會新增至要驗證的 Amazon SES。

```
node ses_verifyemailidentity.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_verifyemailidentity.js)此範例程式碼。

## 驗證網域身分
<a name="ses-examples-verifying-domains"></a>

在此範例中，使用 Node.js 模組來驗證要與 Amazon SES 搭配使用的電子郵件網域。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_verifydomainidentity.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件以傳遞 `SES` 用戶端類別的 `VerifyDomainIdentityCommand` 方法之 `Domain` 參數。若要呼叫 `VerifyDomainIdentityCommand`方法，請叫用 Amazon SES 用戶端服務物件，傳遞參數物件。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
以網域名稱取代 *DOMAIN\$1NAME*。

```
import { VerifyDomainIdentityCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * You must have access to the domain's DNS settings to complete the
 * domain verification process.
 */
const DOMAIN_NAME = postfix(getUniqueName("Domain"), ".example.com");

const createVerifyDomainIdentityCommand = () => {
  return new VerifyDomainIdentityCommand({ Domain: DOMAIN_NAME });
};

const run = async () => {
  const VerifyDomainIdentityCommand = createVerifyDomainIdentityCommand();

  try {
    return await sesClient.send(VerifyDomainIdentityCommand);
  } catch (err) {
    console.log("Failed to verify domain.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。網域會新增至要驗證的 Amazon SES。

```
node ses_verifydomainidentity.js  
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_verifydomainidentity.js)此範例程式碼。

## 刪除身分
<a name="ses-examples-deleting-identities"></a>

在此範例中，使用 Node.js 模組來刪除與 Amazon SES 搭配使用的電子郵件地址或網域。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)範例程式碼。

以檔名 `ses_deleteidentity.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件以傳遞 `SES` 用戶端類別的 `DeleteIdentityCommand` 方法之 `Identity` 參數。若要呼叫 `DeleteIdentityCommand`方法，請建立 `request`以叫用 Amazon SES 用戶端服務物件，並傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *IDENTITY\$1EMAIL* 取代為要刪除之身分的電子郵件。

```
import { DeleteIdentityCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const IDENTITY_EMAIL = "fake@example.com";

const createDeleteIdentityCommand = (identityName) => {
  return new DeleteIdentityCommand({
    Identity: identityName,
  });
};

const run = async () => {
  const deleteIdentityCommand = createDeleteIdentityCommand(IDENTITY_EMAIL);

  try {
    return await sesClient.send(deleteIdentityCommand);
  } catch (err) {
    console.log("Failed to delete identity.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node ses_deleteidentity.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/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/zh_tw/sdk-for-javascript/v3/developer-guide/images/nodeicon.png)

**這個 Node.js 程式碼範例會說明：**
+ 如何取得所有電子郵件範本的清單。
+ 如何擷取和更新電子郵件範本。
+ 如何建立和刪除電子郵件範本。

Amazon SES 可讓您使用電子郵件範本傳送個人化電子郵件訊息。如需如何在 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 模組使用適用於 JavaScript 的 SDK，使用以下`SES`用戶端類別的方法建立和使用電子郵件範本：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListTemplatesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListTemplatesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/CreateTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/CreateTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/GetTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/GetTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/UpdateTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/UpdateTemplateCommand/)

## 先決條件任務
<a name="ses-examples-creating-template-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 列出您的電子郵件範本
<a name="ses-examples-listing-templates"></a>

在此範例中，使用 Node.js 模組建立與 Amazon SES 搭配使用的電子郵件範本。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_listtemplates.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件以傳遞 `SES` 用戶端類別的 `ListTemplatesCommand` 方法之參數。若要呼叫 `ListTemplatesCommand`方法，請叫用 Amazon SES 用戶端服務物件，並傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

```
import { ListTemplatesCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createListTemplatesCommand = (maxItems) =>
  new ListTemplatesCommand({ MaxItems: maxItems });

const run = async () => {
  const listTemplatesCommand = createListTemplatesCommand(10);

  try {
    return await sesClient.send(listTemplatesCommand);
  } catch (err) {
    console.log("Failed to list templates.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。Amazon SES 會傳回範本清單。

```
node ses_listtemplates.js  
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_listtemplates.js)此範例程式碼。

## 取得電子郵件範本
<a name="ses-examples-get-template"></a>

在此範例中，使用 Node.js 模組取得要與 Amazon SES 搭配使用的電子郵件範本。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_gettemplate.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件以傳遞 `SES` 用戶端類別的 `GetTemplateCommand` 方法之 `TemplateName` 參數。若要呼叫 `GetTemplateCommand`方法，請叫用 Amazon SES 用戶端服務物件，傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *TEMPLATE\$1NAME* 取代為要傳回的範本名稱。

```
import { GetTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");

const createGetTemplateCommand = (templateName) =>
  new GetTemplateCommand({ TemplateName: templateName });

const run = async () => {
  const getTemplateCommand = createGetTemplateCommand(TEMPLATE_NAME);

  try {
    return await sesClient.send(getTemplateCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。Amazon SES 會傳回範本詳細資訊。

```
node ses_gettemplate.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_gettemplate.js)此範例程式碼。

## 建立電子郵件範本
<a name="ses-examples-create-template"></a>

在此範例中，使用 Node.js 模組建立與 Amazon SES 搭配使用的電子郵件範本。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_createtemplate.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件以傳遞 `SES` 用戶端類別的 `CreateTemplateCommand` 方法 (包括 `TemplateName`、`HtmlPart`、`SubjectPart` 和 `TextPart`) 之參數。若要呼叫 `CreateTemplateCommand`方法，請叫用 Amazon SES 用戶端服務物件，並傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *TEMPLATE\$1NAME* 取代為新範本的名稱、將 *HtmlPart* 取代為 HTML 標記的電子郵件內容，並將 *SubjectPart* 取代為電子郵件的主旨。

```
import { CreateTemplateCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

const TEMPLATE_NAME = getUniqueName("TestTemplateName");

const createCreateTemplateCommand = () => {
  return new CreateTemplateCommand({
    /**
     * The template feature in Amazon SES is based on the Handlebars template system.
     */
    Template: {
      /**
       * The name of an existing template in Amazon SES.
       */
      TemplateName: TEMPLATE_NAME,
      HtmlPart: `
        <h1>Hello, {{contact.firstName}}!</h1>
        <p>
        Did you know Amazon has a mascot named Peccy?
        </p>
      `,
      SubjectPart: "Amazon Tip",
    },
  });
};

const run = async () => {
  const createTemplateCommand = createCreateTemplateCommand();

  try {
    return await sesClient.send(createTemplateCommand);
  } catch (err) {
    console.log("Failed to create template.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。範本會新增至 Amazon SES。

```
node ses_createtemplate.js  
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_createtemplate.js)此範例程式碼。

## 更新電子郵件範本
<a name="ses-examples-update-template"></a>

在此範例中，使用 Node.js 模組建立與 Amazon SES 搭配使用的電子郵件範本。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)範例程式碼。

以檔名 `ses_updatetemplate.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立一個物件，並搭配需要的 `TemplateName` 參數 (傳遞至 `SES` 用戶端類別的 `UpdateTemplateCommand` 方法之參數)，以傳遞您要在範本中更新的 `Template` 參數值。若要呼叫 `UpdateTemplateCommand`方法，請叫用 Amazon SES 服務物件，並傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *TEMPLATE\$1NAME* 取代為範本的名稱，並將 *HTML\$1PART* 取代為電子郵件的 HTML 標記內容。

```
import { UpdateTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");
const HTML_PART = "<h1>Hello, World!</h1>";

const createUpdateTemplateCommand = () => {
  return new UpdateTemplateCommand({
    Template: {
      TemplateName: TEMPLATE_NAME,
      HtmlPart: HTML_PART,
      SubjectPart: "Example",
      TextPart: "Updated template text.",
    },
  });
};

const run = async () => {
  const updateTemplateCommand = createUpdateTemplateCommand();

  try {
    return await sesClient.send(updateTemplateCommand);
  } catch (err) {
    console.log("Failed to update template.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。Amazon SES 會傳回範本詳細資訊。

```
node ses_updatetemplate.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_updatetemplate.js)此範例程式碼。

## 刪除電子郵件範本
<a name="ses-examples-delete-template"></a>

在此範例中，使用 Node.js 模組建立與 Amazon SES 搭配使用的電子郵件範本。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_deletetemplate.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立物件以傳遞需要的 `TemplateName` 參數至 `SES` 用戶端類別的 `DeleteTemplateCommand` 方法。若要呼叫 `DeleteTemplateCommand`方法，請叫用 Amazon SES 服務物件，傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *TEMPLATE\$1NAME* 取代為要刪除的範本名稱。

```
import { DeleteTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");

const createDeleteTemplateCommand = (templateName) =>
  new DeleteTemplateCommand({ TemplateName: templateName });

const run = async () => {
  const deleteTemplateCommand = createDeleteTemplateCommand(TEMPLATE_NAME);

  try {
    return await sesClient.send(deleteTemplateCommand);
  } catch (err) {
    console.log("Failed to delete template.", err);
    return err;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。Amazon SES 會傳回範本詳細資訊。

```
node ses_deletetemplate.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/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/zh_tw/sdk-for-javascript/v3/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 模組使用適用於 JavaScript 的 SDK，使用以下`SES`用戶端類別的方法建立和使用電子郵件範本：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendEmailCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendTemplatedEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendTemplatedEmailCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendBulkTemplatedEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendBulkTemplatedEmailCommand/)

## 先決條件任務
<a name="ses-examples-sending-emails-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 電子郵件訊息傳送要求
<a name="ses-examples-sending-msail-reqs"></a>

Amazon SES 會撰寫電子郵件訊息，並立即將訊息排入佇列以供傳送。若要使用 `SendEmailCommand` 方法傳送電子郵件，您的訊息必須符合下列需求：
+ 您必須從已驗證的電子郵件地址或網域傳送訊息。如果您要使用非驗證的地址或網域來傳送電子郵件，則該操作會導致 `"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)。
+ 訊息的總大小 (包括附件) 必須小於 10 MB。
+ 該訊息至少必須含有一個收件人電子郵件地址。收件人地址可為 To (收件人)：地址、CC (副本)：地址或 BCC (密件副本)：地址。如果收件人電子郵件地址無效 （即不是 的格式`UserName@[SubDomain.]Domain.TopLevelDomain`)，即使訊息包含其他有效的收件人，也會拒絕整個訊息。
+ 訊息不能包含跨收件人：、CC： 和 BCC： 欄位的 50 個以上的收件人。若您需要傳送電子郵件訊息給更多的收件人，則您必須將收件人清單分成 50 人或更少人的群組，然後再多次呼叫 `sendEmail` 方法以傳送訊息至個別群組。

## 傳送電子郵件
<a name="ses-examples-sendmail"></a>

在此範例中，使用 Node.js 模組以搭配 Amazon SES 傳送電子郵件。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_sendemail.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立 物件，以將定義要傳送之電子郵件的參數值傳遞至`SES`用戶端類別的 `SendEmailCommand`方法，包括傳送者和接收者地址、主旨和電子郵件內文。若要呼叫 `SendEmailCommand`方法，請叫用 Amazon SES 服務物件，傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *toAddress* 取代為傳送電子郵件的地址，並將 *fromAddress* 取代為傳送電子郵件的地址。

```
import { SendEmailCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createSendEmailCommand = (toAddress, fromAddress) => {
  return new SendEmailCommand({
    Destination: {
      /* required */
      CcAddresses: [
        /* more items */
      ],
      ToAddresses: [
        toAddress,
        /* more To-email addresses */
      ],
    },
    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: "EMAIL_SUBJECT",
      },
    },
    Source: fromAddress,
    ReplyToAddresses: [
      /* more items */
    ],
  });
};

const run = async () => {
  const sendEmailCommand = createSendEmailCommand(
    "recipient@example.com",
    "sender@example.com",
  );

  try {
    return await sesClient.send(sendEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。電子郵件會排入佇列以供 Amazon SES 傳送。

```
node ses_sendemail.js 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendemail.js)範例程式碼。

## 使用範本傳送電子郵件
<a name="ses-examples-sendtemplatedemail"></a>

在此範例中，使用 Node.js 模組以搭配 Amazon SES 傳送電子郵件。以檔名 `ses_sendtemplatedemail.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立一個物件以傳遞定義欲傳送電子郵件的參數值，包括寄件者和接收者地址、主旨、電子郵件本文 (純文字和 HTML 格式)，至 `SES` 用戶端類別的 `SendTemplatedEmailCommand` 方法。若要呼叫 `SendTemplatedEmailCommand`方法，請叫用 Amazon SES 用戶端服務物件，並傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *REGION* 取代為您的 AWS 區域，將 *USER* 取代為要傳送電子郵件的名稱和電子郵件地址，將 *VERIFIED\$1EMAIL* 取代為傳送電子郵件的地址，將 *TEMPLATE\$1NAME* 取代為範本的名稱。

```
import { SendTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL = postfix(getUniqueName("Bilbo"), "@example.com");

const USER = { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL };

/**
 *
 * @param { { emailAddress: string, firstName: string } } user
 * @param { string } templateName - The name of an existing template in Amazon SES.
 * @returns { SendTemplatedEmailCommand }
 */
const createReminderEmailCommand = (user, templateName) => {
  return new SendTemplatedEmailCommand({
    /**
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{contact.firstName}},</h1><p>Don't forget about the party gifts!</p>
     * Destination: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destination: { ToAddresses: [user.emailAddress] },
    TemplateData: JSON.stringify({ contact: { firstName: user.firstName } }),
    Source: VERIFIED_EMAIL,
    Template: templateName,
  });
};

const run = async () => {
  const sendReminderEmailCommand = createReminderEmailCommand(
    USER,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendReminderEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。電子郵件會排入佇列以供 Amazon SES 傳送。

```
node ses_sendtemplatedemail.js 
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendtemplatedemail.js)此範例程式碼。

## 使用範本傳送大量電子郵件
<a name="ses-examples-sendbulktemplatedemail"></a>

在此範例中，使用 Node.js 模組以搭配 Amazon SES 傳送電子郵件。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`sesClient.js`。複製並貼上以下程式碼，以建立 Amazon SES 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/libs/sesClient.js)此範例程式碼。

以檔名 `ses_sendbulktemplatedemail.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立 物件，以將定義要傳送之電子郵件的參數值傳遞至`SES`用戶端類別的 `SendBulkTemplatedEmailCommand`方法，包括傳送者和接收者地址、主旨和電子郵件內文。若要呼叫 `SendBulkTemplatedEmailCommand`方法，請叫用 Amazon SES 服務物件，傳遞參數。

**注意**  
此範例會匯入並使用所需的 AWS Service V3 套件用戶端、V3 命令，並以非同步/等待模式使用 `send`方法。您可以使用 V2 命令來建立此範例，方法是進行一些次要變更。如需詳細資訊，請參閱[使用 v3 命令](migrating.md#using_v3_commands)。

**注意**  
將 *USERS* 取代為要傳送電子郵件的名稱和電子郵件地址、將 *VERIFIED\$1EMAIL\$11* 取代為傳送電子郵件的地址，並將 *TEMPLATE\$1NAME* 取代為範本的名稱。

```
import { SendBulkTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL_1 = postfix(getUniqueName("Bilbo"), "@example.com");
const VERIFIED_EMAIL_2 = postfix(getUniqueName("Frodo"), "@example.com");

const USERS = [
  { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL_1 },
  { firstName: "Frodo", emailAddress: VERIFIED_EMAIL_2 },
];

/**
 *
 * @param { { emailAddress: string, firstName: string }[] } users
 * @param { string } templateName the name of an existing template in SES
 * @returns { SendBulkTemplatedEmailCommand }
 */
const createBulkReminderEmailCommand = (users, templateName) => {
  return new SendBulkTemplatedEmailCommand({
    /**
     * Each 'Destination' uses a corresponding set of replacement data. We can map each user
     * to a 'Destination' and provide user specific replacement data to create personalized emails.
     *
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{name}},</h1><p>Don't forget about the party gifts!</p>
     * Destination 1: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     * Destination 2: <h1>Hello Frodo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destinations: users.map((user) => ({
      Destination: { ToAddresses: [user.emailAddress] },
      ReplacementTemplateData: JSON.stringify({ name: user.firstName }),
    })),
    DefaultTemplateData: JSON.stringify({ name: "Shireling" }),
    Source: VERIFIED_EMAIL_1,
    Template: templateName,
  });
};

const run = async () => {
  const sendBulkTemplateEmailCommand = createBulkReminderEmailCommand(
    USERS,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendBulkTemplateEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

若要執行範例，請在命令提示中輸入以下內容。電子郵件會排入佇列以供 Amazon SES 傳送。

```
node ses_sendbulktemplatedemail.js
```

您可以在 [ GitHub 上找到](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/ses/src/ses_sendbulktemplatedemail.js)此範例程式碼。

# Amazon Simple Notification Service 範例
<a name="sns-examples"></a>

Amazon Simple Notification Service (Amazon SNS) 是一種 Web 服務，可協調和管理訊息傳遞或傳送至訂閱端點或用戶端。

在 Amazon SNS 中，有兩種類型的用戶端：發佈者和訂閱者，也稱為生產者和消費者。

![\[JavaScript 環境、軟體開發套件和 Amazon SNS 之間的關係\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/code-samples-sns.png)


發佈者透過製作並傳送訊息到主題 (其為邏輯存取點和通訊管道) 與訂閱者進行非同步的通訊。訂閱者 （網路伺服器、電子郵件地址、Amazon SQS 佇列、 AWS Lambda 函數） 在訂閱主題時，會透過其中一個支援的通訊協定 (Amazon SQS、HTTP/S、電子郵件、簡訊 AWS Lambda) 取用或接收訊息或通知。

Amazon SNS 的 JavaScript API 透過[類別：SNS ](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SNS/)公開。

**Topics**
+ [在 Amazon SNS 中管理主題](sns-examples-managing-topics.md)
+ [在 Amazon SNS 中發佈訊息](sns-examples-publishing-messages.md)
+ [在 Amazon SNS 中管理訂閱](sns-examples-subscribing-unsubscribing-topics.md)
+ [使用 Amazon SNS 傳送簡訊](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/zh_tw/sdk-for-javascript/v3/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 模組使用適用於 JavaScript 的 SDK 來管理使用下列`SNS`用戶端類別方法的主題：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CreateTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CreateTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/)

## 先決條件任務
<a name="sns-examples-managing-topics-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 建立主題
<a name="sns-examples-managing-topics-createtopic"></a>

在此範例中，使用 Node.js 模組來建立 Amazon SNS 主題。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `create-topic.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立一個物件，藉此將新主題的 `Name` 傳遞至 `SNS` 用戶端類別的 `CreateTopicCommand` 方法。若要呼叫 `CreateTopicCommand`方法，請建立叫用 Amazon SNS 服務物件、傳遞參數物件的非同步函數。`data` 傳回的 包含主題的 ARN。

**注意**  
將 *TOPIC\$1NAME* 取代為主題的名稱。

```
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicName - The name of the topic to create.
 */
export const createTopic = async (topicName = "TOPIC_NAME") => {
  const response = await snsClient.send(
    new CreateTopicCommand({ Name: topicName }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node create-topic.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/create-topic.js)範例程式碼。

## 列出 主題
<a name="sns-examples-managing-topics-listtopics"></a>

在此範例中，使用 Node.js 模組列出所有 Amazon SNS 主題。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `list-topics.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立空白物件，並將其傳遞至 `SNS` 用戶端類別的 `ListTopicsCommand` 方法。若要呼叫 `ListTopicsCommand`方法，請建立叫用 Amazon SNS 服務物件、傳遞參數物件的非同步函數。`data` 傳回的 包含主題 Amazon Resource Name (ARNs) 的陣列。

```
import { ListTopicsCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const listTopics = async () => {
  const response = await snsClient.send(new ListTopicsCommand({}));
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '936bc5ad-83ca-53c2-b0b7-9891167b909e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Topics: [ { TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic' } ]
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node list-topics.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-topics.js)找到這個範本程式碼。

## 刪除主題
<a name="sns-examples-managing-topics-deletetopic"></a>

在此範例中，使用 Node.js 模組來刪除 Amazon SNS 主題。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `delete-topic.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立包含欲刪除主題 `TopicArn` 的物件，並將其傳遞至 `SNS` 用戶端類別的 `DeleteTopicCommand` 方法。若要呼叫 `DeleteTopicCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為您要刪除之主題的 Amazon Resource Name (ARN)。

```
import { DeleteTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic to delete.
 */
export const deleteTopic = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new DeleteTopicCommand({ TopicArn: topicArn }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'a10e2886-5a8f-5114-af36-75bd39498332',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node delete-topic.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/delete-topic.js)範例程式碼。

## 取得主題屬性
<a name="sns-examples-managing-topicsgettopicattributes"></a>

在此範例中，使用 Node.js 模組擷取 Amazon SNS 主題的屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `get-topic-attributes.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含欲刪除主題 `TopicArn` 的物件，並將其傳遞至 `SNS` 用戶端類別的 `GetTopicAttributesCommand` 方法。若要呼叫 `GetTopicAttributesCommand`方法，請叫用 Amazon SNS 用戶端服務物件，並傳遞參數物件。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 ARN。

```
import { GetTopicAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic to retrieve attributes for.
 */
export const getTopicAttributes = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new GetTopicAttributesCommand({
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '36b6a24e-5473-5d4e-ac32-ff72d9a73d94',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Attributes: {
  //     Policy: '{...}',
  //     Owner: 'xxxxxxxxxxxx',
  //     SubscriptionsPending: '1',
  //     TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic',
  //     TracingConfig: 'PassThrough',
  //     EffectiveDeliveryPolicy: '{"http":{"defaultHealthyRetryPolicy":{"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0,"numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false,"defaultRequestPolicy":{"headerContentType":"text/plain; charset=UTF-8"}}}',
  //     SubscriptionsConfirmed: '0',
  //     DisplayName: '',
  //     SubscriptionsDeleted: '1'
  //   }
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node get-topic-attributes.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-topic-attributes.js)範例程式碼。

## 設定主題屬性
<a name="sns-examples-managing-topicssttopicattributes"></a>

在此範例中，使用 Node.js 模組來設定 Amazon SNS 主題的可變屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `set-topic-attributes.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立一個物件，其中包含用來更新屬性的參數，包括要設定屬性的主題 `TopicArn`、要設定的屬性名稱，以及該屬性的新數值。您只能設定 `Policy`、`DisplayName` 和 `DeliveryPolicy` 屬性。接著，將參數傳遞至 `SNS` 用戶端類別的 `SetTopicAttributesCommand` 方法。若要呼叫 `SetTopicAttributesCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *ATTRIBUTE\$1NAME* 取代為您設定的屬性名稱、將 *TOPIC\$1ARN* 取代為您要設定屬性之主題的 Amazon Resource Name (ARN)，並將 *NEW\$1ATTRIBUTE\$1VALUE* 取代為該屬性的新值。

```
import { SetTopicAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const setTopicAttributes = async (
  topicArn = "TOPIC_ARN",
  attributeName = "DisplayName",
  attributeValue = "Test Topic",
) => {
  const response = await snsClient.send(
    new SetTopicAttributesCommand({
      AttributeName: attributeName,
      AttributeValue: attributeValue,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node set-topic-attributes.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-topic-attributes.js)範例程式碼。

# 在 Amazon SNS 中發佈訊息
<a name="sns-examples-publishing-messages"></a>

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

**這個 Node.js 程式碼範例會說明：**
+ 如何將訊息發佈至 Amazon SNS 主題。

## 使用案例
<a name="sns-examples-publishing-messages-scenario"></a>

在此範例中，您會使用一系列 Node.js 模組，將訊息從 Amazon SNS 發佈至主題端點、電子郵件或電話號碼。Node.js 模組使用適用於 JavaScript 的 SDK，使用此`SNS`用戶端類別的方法傳送訊息：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/)

## 先決條件任務
<a name="sns-examples-publishing-messages-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 發佈訊息至 SNS 主題
<a name="sns-examples-publishing-text-messages"></a>

在此範例中，使用 Node.js 模組將訊息發佈至 Amazon SNS 主題。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `publish-topic.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含發佈訊息參數的物件，包括訊息文字和 Amazon SNStopic 的 Amazon Resource Name (ARN)。如需可用簡訊屬性的詳細資訊，請參閱 [SetSMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setSMSAttributes-property)。

將參數傳遞至`SNS`用戶端類別的 `PublishCommand`方法。 建立非同步函數，叫用 Amazon SNS 用戶端服務物件，並傳遞參數物件。

**注意**  
將 *MESSAGE\$1TEXT* 取代為訊息文字，並將 *TOPIC\$1ARN* 取代為 SNS 主題的 ARN。

```
import { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {string} topicArn - The ARN of the topic to which you would like to publish.
 */
export const publish = async (
  message = "Hello from SNS!",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node publish-topic.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/publish-topic.js)範例程式碼。

# 在 Amazon SNS 中管理訂閱
<a name="sns-examples-subscribing-unsubscribing-topics"></a>

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

**這個 Node.js 程式碼範例會說明：**
+ 如何列出 Amazon SNS 主題的所有訂閱。
+ 如何訂閱電子郵件地址、應用程式端點或 AWS Lambda 函數至 Amazon SNS 主題。
+ 如何取消訂閱 Amazon SNS 主題。

## 使用案例
<a name="sns-examples-subscribing-unsubscribing-topics-scenario"></a>

在此範例中，您會使用一系列 Node.js 模組，將通知訊息發佈至 Amazon SNS 主題。Node.js 模組使用適用於 JavaScript 的 SDK 來管理使用下列`SNS`用戶端類別方法的主題：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/)

## 先決條件任務
<a name="sns-examples-subscribing-unsubscribing-topics-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 列出主題的訂閱
<a name="sns-examples-list-subscriptions-email"></a>

在此範例中，使用 Node.js 模組列出 Amazon SNS 主題的所有訂閱。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `list-subscriptions-by-topic.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立一個物件，其中包含要列出訂閱的主題 `TopicArn` 參數。接著，將參數傳遞至 `SNS` 用戶端類別的 `ListSubscriptionsByTopicCommand` 方法。若要呼叫 `ListSubscriptionsByTopicCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件的非同步函數，並傳遞參數物件。

**注意**  
將 *TOPIC\$1ARN* 取代為您想要列出訂閱之主題的 Amazon Resource Name (ARN)。

```
import { ListSubscriptionsByTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic for which you wish to list subscriptions.
 */
export const listSubscriptionsByTopic = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new ListSubscriptionsByTopicCommand({ TopicArn: topicArn }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '0934fedf-0c4b-572e-9ed2-a3e38fadb0c8',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Subscriptions: [
  //     {
  //       SubscriptionArn: 'PendingConfirmation',
  //       Owner: '901487484989',
  //       Protocol: 'email',
  //       Endpoint: 'corepyle@amazon.com',
  //       TopicArn: 'arn:aws:sns:us-east-1:901487484989:mytopic'
  //     }
  //   ]
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node list-subscriptions-by-topic.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js)範例程式碼。

## 使用電子郵件地址訂閱主題
<a name="sns-examples-subscribing-email"></a>

在此範例中，使用 Node.js 模組來訂閱電子郵件地址，以便接收來自 Amazon SNS 主題的 SMTP 電子郵件訊息。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `subscribe-email.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含 `Protocol` 參數的物件，以便指定 `email` 通訊協定、要訂閱的主題 `TopicArn`，以及要做為訊息 `Endpoint` 的電子郵件地址。接著，將參數傳遞至 `SNS` 用戶端類別的 `SubscribeCommand` 方法。您可以使用 `subscribe`方法將數個不同的端點訂閱 Amazon SNS 主題，這取決於傳遞的參數所使用的值，因為本主題中的其他範例會顯示。

若要呼叫 `SubscribeCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件的非同步函數，並傳遞參數物件。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (ARN)，並將 *EMAIL\$1ADDRESS* 取代為要訂閱的電子郵件地址。

```
import { SubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription.
 * @param {string} emailAddress - The email address that is subscribed to the topic.
 */
export const subscribeEmail = async (
  topicArn = "TOPIC_ARN",
  emailAddress = "usern@me.com",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "email",
      TopicArn: topicArn,
      Endpoint: emailAddress,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node subscribe-email.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-email.js)範例程式碼。

### 確認訂閱
<a name="sns-confirm-subscription-email"></a>

在此範例中，使用 Node.js 模組驗證端點擁有者接收電子郵件的意圖，方法是驗證先前訂閱動作傳送至端點的字符。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `confirm-subscription.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

定義參數，包括 `TOPIC_ARN`和 `TOKEN`，並為 定義 `TRUE`或 `FALSE` 的值`AuthenticateOnUnsubscribe`。

權杖是在上一個`SUBSCRIBE`動作期間傳送給端點擁有者的短期權杖。例如，對於電子郵件端點， `TOKEN` 位於傳送給電子郵件擁有者的確認訂閱電子郵件 URL 中。例如， `abc123` 是下列 URL 中的字符。

![\[Amazon Web Services Simple Notification Service subscription confirmation page.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/token.png)


若要呼叫 `ConfirmSubscriptionCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (ARN)，將 *TOKEN* 取代為先前`Subscribe`動作中傳送給端點擁有者的 URL 中的字符值，並將 *AuthenticateOnUnsubscribe*. 定義為 `TRUE`或 的值`FALSE`。

```
import { ConfirmSubscriptionCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} token - This token is sent the subscriber. Only subscribers
 *                         that are not AWS services (HTTP/S, email) need to be confirmed.
 * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription.
 */
export const confirmSubscription = async (
  token = "TOKEN",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    // A subscription only needs to be confirmed if the endpoint type is
    // HTTP/S, email, or in another AWS account.
    new ConfirmSubscriptionCommand({
      Token: token,
      TopicArn: topicArn,
      // If this is true, the subscriber cannot unsubscribe while unauthenticated.
      AuthenticateOnUnsubscribe: "false",
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '4bb5bce9-805a-5517-8333-e1d2cface90b',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node confirm-subscription.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/confirm-subscription.js)範例程式碼。

## 使用應用程式端點訂閱主題
<a name="sns-examples-subscribing-apps"></a>

在此範例中，使用 Node.js 模組訂閱行動應用程式端點，以便接收來自 Amazon SNS 主題的通知。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `subscribe-app.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的模組和套件。

建立包含 `Protocol` 參數的物件來指定`application`通訊協定、要訂閱主題`TopicArn`的 ，以及 `Endpoint` 參數行動應用程式端點的 Amazon Resource Name (ARN)。接著，將參數傳遞至 `SNS` 用戶端類別的 `SubscribeCommand` 方法。

若要呼叫 `SubscribeCommand`方法，請建立叫用 Amazon SNS 服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (ARN)，並將 *MOBILE\$1ENDPOINT\$1ARN* 取代為您訂閱主題的端點。

```
import { SubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to.
 * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created
 *                            when an application registers for notifications.
 */
export const subscribeApp = async (
  topicArn = "TOPIC_ARN",
  endpoint = "ENDPOINT",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "application",
      TopicArn: topicArn,
      Endpoint: endpoint,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node subscribe-app.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-app.js)範例程式碼。

## 訂閱 Lambda 函數至主題
<a name="sns-examples-subscribing-lambda"></a>

在此範例中，使用 Node.js 模組來訂閱 AWS Lambda 函數，以便接收來自 Amazon SNS 主題的通知。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `subscribe-lambda.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。

建立包含 `Protocol` 參數的物件，指定`lambda`通訊協定、要訂閱的主題`TopicArn`的 ，以及 AWS Lambda 函數的 Amazon Resource Name (ARN) 做為 `Endpoint` 參數。接著，將參數傳遞至 `SNS` 用戶端類別的 `SubscribeCommand` 方法。

若要呼叫 `SubscribeCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為主題的 Amazon Resource Name (ARN)，並將 *LAMBDA\$1FUNCTION\$1ARN* 取代為 Lambda 函數的 Amazon Resource Name (ARN)。

```
import { SubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to.
 * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function.
 */
export const subscribeLambda = async (
  topicArn = "TOPIC_ARN",
  endpoint = "ENDPOINT",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "lambda",
      TopicArn: topicArn,
      Endpoint: endpoint,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node subscribe-lambda.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-lambda.js)範例程式碼。

## 取消訂閱主題
<a name="sns-examples-unsubscribing"></a>

在此範例中，使用 Node.js 模組取消訂閱 Amazon SNS 主題訂閱。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `unsubscribe.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。

建立包含 `SubscriptionArn` 參數的物件，指定要取消訂閱的訂閱 Amazon Resource Name (ARN)。接著，將參數傳遞至 `SNS` 用戶端類別的 `UnsubscribeCommand` 方法。

若要呼叫 `UnsubscribeCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
以訂閱的 Amazon Resource Name (*ARN) 取代 TOPIC\$1SUBSCRIPTION\$1*ARN 以取消訂閱。

```
import { UnsubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} subscriptionArn - The ARN of the subscription to cancel.
 */
const unsubscribe = async (
  subscriptionArn = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
) => {
  const response = await snsClient.send(
    new UnsubscribeCommand({
      SubscriptionArn: subscriptionArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '0178259a-9204-507c-b620-78a7570a44c6',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node unsubscribe.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/unsubscribe.js)範例程式碼。

# 使用 Amazon SNS 傳送簡訊
<a name="sns-examples-sending-sms"></a>

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

**這個 Node.js 程式碼範例會說明：**
+ 如何取得和設定 Amazon SNS 的簡訊偏好設定。
+ 如何檢查電話號碼是否選擇不要接收簡訊。
+ 如何取得選擇不要接收簡訊的電話號碼清單。
+ 如何傳送簡訊。

## 使用案例
<a name="sns-examples-sending-sms-scenario"></a>

您可以使用 Amazon SNS 傳送文字訊息或簡訊至啟用簡訊功能的裝置。您可以直接傳送訊息至一組電話號碼，或一次傳送一則訊息至多組電話號碼，只要訂閱那些電話號碼到主題並且傳送您的訊息到該主題即可。

在此範例中，您會使用一系列 Node.js 模組，將 SMS 文字訊息從 Amazon SNS 發佈至啟用 SMS 的裝置。Node.js 模組使用適用於 JavaScript 的 SDK，以`SNS`用戶端類別的下列方法發佈 SMS 訊息：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/)

## 先決條件任務
<a name="sns-examples-sending-sms-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循 [ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 取得簡訊屬性
<a name="sending-sms-getattributes"></a>

使用 Amazon SNS 指定簡訊的偏好設定，例如如何最佳化交付 （用於成本或可靠交付）、每月花費限制、如何記錄訊息交付，以及是否訂閱每日簡訊用量報告。系統會擷取這些偏好設定，並將其設定為 Amazon SNS 的 SMS 屬性。

在此範例中，使用 Node.js 模組取得 Amazon SNS 中目前的 SMS 屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `get-sms-attributes.js` 建立一個 Node.js 模組。

如先前所示設定 SDK，包括下載所需的用戶端和套件。建立一個物件，其中包含用來取得簡訊屬性的參數，包括要擷取的個別屬性名稱。如需可用 SMS 屬性的詳細資訊，請參閱《Amazon Simple Notification Service API 參考》中的 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)。

此範例會取得 `DefaultSMSType` 屬性，其可控制簡訊的傳送方式；`Promotional` 會將訊息交付最佳化以降低成本，而 `Transactional` 則會將訊息交付最佳化以達到最高的可靠性。接著，將參數傳遞至 `SNS` 用戶端類別的 `SetTopicAttributesCommand` 方法。若要呼叫 `SetSMSAttributesCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *ATTRIBUTE\$1NAME* 取代為 屬性的名稱。

```
import { GetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const getSmsAttributes = async () => {
  const response = await snsClient.send(
    // If you have not modified the account-level mobile settings of SNS,
    // the DefaultSMSType is undefined. For this example, it was set to
    // Transactional.
    new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   attributes: { DefaultSMSType: 'Transactional' }
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node get-sms-attributes.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-sms-attributes.js)範例程式碼。

## 設定簡訊屬性
<a name="sending-sms-setattributes"></a>

在此範例中，使用 Node.js 模組取得 Amazon SNS 中目前的 SMS 屬性。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

 以檔名 `set-sms-attribute-type.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。建立一個物件，其中包含用來設定簡訊屬性的參數，包括要設定的個別屬性名稱，以及要為每個屬性設定的值。如需可用 SMS 屬性的詳細資訊，請參閱《Amazon Simple Notification Service API 參考》中的 [ SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)。

此範例將 `DefaultSMSType` 屬性設為 `Transactional`，藉此將訊息交付最佳化為達成最高的可靠性。接著，將參數傳遞至 `SNS` 用戶端類別的 `SetTopicAttributesCommand` 方法。若要呼叫 `SetSMSAttributesCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

```
import { SetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {"Transactional" | "Promotional"} defaultSmsType
 */
export const setSmsType = async (defaultSmsType = "Transactional") => {
  const response = await snsClient.send(
    new SetSMSAttributesCommand({
      attributes: {
        // Promotional – (Default) Noncritical messages, such as marketing messages.
        // Transactional – Critical messages that support customer transactions,
        // such as one-time passcodes for multi-factor authentication.
        DefaultSMSType: defaultSmsType,
      },
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '1885b977-2d7e-535e-8214-e44be727e265',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node set-sms-attribute-type.js 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js)範例程式碼。

## 檢查電話號碼是否已停止接收
<a name="sending-sms-checkifphonenumberisoptedout"></a>

在此範例中，您可以使用 Node.js 模組來檢查電話號碼是否選擇不要接收簡訊。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `check-if-phone-number-is-opted-out.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。建立一個物件，其中包含要以參數形式檢查的電話號碼。

此範例會設定 `PhoneNumber` 參數，藉此指定要檢查的電話號碼。接著，將物件傳遞至 `SNS` 用戶端類別的 `CheckIfPhoneNumberIsOptedOutCommand` 方法。若要呼叫 `CheckIfPhoneNumberIsOptedOutCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  

將 *PHONE\$1NUMBER* 取代為電話號碼。

```
import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns";

import { snsClient } from "../libs/snsClient.js";

export const checkIfPhoneNumberIsOptedOut = async (
  phoneNumber = "5555555555",
) => {
  const command = new CheckIfPhoneNumberIsOptedOutCommand({
    phoneNumber,
  });

  const response = await snsClient.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   isOptedOut: false
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node check-if-phone-number-is-opted-out.js 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js)範例程式碼。

## 列出已停止接收的電話號碼
<a name="sending-sms-listphonenumbersoptedout"></a>

在此範例中，您可以使用 Node.js 模組來取得選擇不要接收簡訊的電話號碼清單。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `list-phone-numbers-opted-out.js` 建立一個 Node.js 模組。依前述內容設定軟體開發套件。建立空白物件做為參數。

接著，將物件傳遞至 `SNS` 用戶端類別的 `ListPhoneNumbersOptedOutCommand` 方法。若要呼叫 `ListPhoneNumbersOptedOutCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

```
import { ListPhoneNumbersOptedOutCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const listPhoneNumbersOptedOut = async () => {
  const response = await snsClient.send(
    new ListPhoneNumbersOptedOutCommand({}),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '44ff72fd-1037-5042-ad96-2fc16601df42',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   phoneNumbers: ['+15555550100']
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node list-phone-numbers-opted-out.js 
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js)範例程式碼。

## 發佈簡訊
<a name="sending-sms-publishsms"></a>

在此範例中，Node.js 模組可用來傳送簡訊至電話號碼。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.js`。複製並貼上以下程式碼，以建立 Amazon SNS 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)範例程式碼。

以檔名 `publish-sms.js` 建立一個 Node.js 模組。如先前所示設定 SDK，包括安裝所需的用戶端和套件。建立包含 `Message` 和 `PhoneNumber` 參數的物件。

當您傳送簡訊時，請指定使用 E.164 格式的電話號碼。E。164 是電話號碼結構的標準，用於國際電信通訊。遵照此格式的電話號碼可以有 15 位數的上限限制，前面加上加號 (\$1) 字元和國碼。例如，E.164 格式的美國電話號碼顯示為 \$11001XXX5550100。

此範例會設定 `PhoneNumber` 參數，藉此指定要傳送訊息的電話號碼。接著，將物件傳遞至 `SNS` 用戶端類別的 `PublishCommand` 方法。若要呼叫 `PublishCommand`方法，請建立叫用 Amazon SNS 服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TEXT\$1MESSAGE* 取代為文字訊息，並將 *PHONE\$1NUMBER* 取代為電話號碼。

```
import { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {*} phoneNumber - The phone number to send the message to.
 */
export const publish = async (
  message = "Hello from SNS!",
  phoneNumber = "+15555555555",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      // One of PhoneNumber, TopicArn, or TargetArn must be specified.
      PhoneNumber: phoneNumber,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '7410094f-efc7-5f52-af03-54737569ab77',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

若要執行範例，請在命令提示中輸入以下內容。

```
node publish-sms.js
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/publish-sms.js)範例程式碼。

# Amazon Transcribe 範例
<a name="Transcribe-examples"></a>

Amazon Transcribe 可讓開發人員輕鬆地將語音新增至其應用程式的文字功能。

![\[JavaScript 環境、軟體開發套件和 Amazon Transcribe 之間的關係\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/code-samples-transcribe.png)


Amazon Transcribe 的 JavaScript API 透過 [TranscribeService](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/Transcribe/) 用戶端類別公開。

**Topics**
+ [Amazon Transcribe 範例](transcribe-examples-section.md)
+ [Amazon Transcribe 醫療範例](transcribe-medical-examples-section.md)

# Amazon Transcribe 範例
<a name="transcribe-examples-section"></a>

在此範例中，一系列 Node.js 模組用於使用下列`TranscribeService`用戶端類別方法建立、列出和刪除轉錄任務：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartTranscriptionJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/)

如需 Amazon Transcribe 使用者的詳細資訊，請參閱 [Amazon Transcribe 開發人員指南](https://docs.aws.amazon.com//transcribe/latest/dg/what-is-transcribe.html)。

## 先決條件任務
<a name="transcribe-example-transcription-jobs"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)

## 啟動 Amazon Transcribe 任務
<a name="transcribe-start-transcription"></a>

此範例示範如何使用 啟動 Amazon Transcribe 轉錄任務 適用於 JavaScript 的 AWS SDK。如需詳細資訊，請參閱 [StartTranscriptionJobCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartTranscriptionJobCommand/)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`transcribeClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Transcribe 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js)範例程式碼。

以檔名 `transcribe-create-job.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。建立參數物件，指定必要的參數。使用 `StartMedicalTranscriptionJobCommand`命令啟動任務。

**注意**  
將 *MEDICAL\$1JOB\$1NAME* 取代為轉錄任務的名稱。針對 *OUTPUT\$1BUCKET\$1NAME*，指定儲存輸出的 Amazon S3 儲存貯體。針對 *JOB\$1TYPE*，指定任務類型。針對 *SOURCE\$1LOCATION*，指定來源檔案的位置。針對 *SOURCE\$1FILE\$1LOCATION*，指定輸入媒體檔案的位置。

```
// Import the required AWS SDK clients and commands for Node.js
import { StartTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  TranscriptionJobName: "JOB_NAME",
  LanguageCode: "LANGUAGE_CODE", // For example, 'en-US'
  MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav'
  Media: {
    MediaFileUri: "SOURCE_LOCATION",
    // For example, "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav"
  },
  OutputBucketName: "OUTPUT_BUCKET_NAME",
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new StartTranscriptionJobCommand(params),
    );
    console.log("Success - put", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node transcribe-create-job.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_create_job.js)找到這個範本程式碼。

## 列出 Amazon Transcribe 任務
<a name="transcribe-list-jobs"></a>

此範例示範如何使用 列出 Amazon Transcribe 轉錄任務 適用於 JavaScript 的 AWS SDK。如需您可以修改哪些其他設定的詳細資訊，請參閱 [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`transcribeClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Transcribe 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js)範例程式碼。

以檔名 `transcribe-list-jobs.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。使用必要的參數建立參數物件。

**注意**  
將 *KEY\$1WORD* 取代為傳回任務名稱必須包含的關鍵字。

```
// Import the required AWS SDK clients and commands for Node.js

import { ListTranscriptionJobsCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  JobNameContains: "KEYWORD", // Not required. Returns only transcription
  // job names containing this string
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new ListTranscriptionJobsCommand(params),
    );
    console.log("Success", data.TranscriptionJobSummaries);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node transcribe-list-jobs.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_list_jobs.js)找到這個範本程式碼。

## 刪除 Amazon Transcribe 任務
<a name="transcribe-delete-job"></a>

此範例說明如何使用 刪除 Amazon Transcribe 轉錄任務 適用於 JavaScript 的 AWS SDK。如需選用的詳細資訊，請參閱 [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`transcribeClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Transcribe 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import  { TranscribeClient }  from  "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Transcribe service object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js)範例程式碼。

以檔名 `transcribe-delete-job.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。指定 AWS 區域，以及您要刪除的任務名稱。

**注意**  
將 *JOB\$1NAME* 取代為要刪除的任務名稱。

```
// Import the required AWS SDK clients and commands for Node.js
import { DeleteTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  TranscriptionJobName: "JOB_NAME", // Required. For example, 'transciption_demo'
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new DeleteTranscriptionJobCommand(params),
    );
    console.log("Success - deleted");
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node transcribe-delete-job.js  
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_delete_job.js)找到這個範本程式碼。

# Amazon Transcribe 醫療範例
<a name="transcribe-medical-examples-section"></a>

在此範例中，一系列 Node.js 模組用於使用下列`TranscribeService`用戶端類別方法建立、列出和刪除醫療轉錄任務：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartMedicalTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartMedicalTranscriptionJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/)

如需 Amazon Transcribe 使用者的詳細資訊，請參閱 [Amazon Transcribe 開發人員指南](https://docs.aws.amazon.com//transcribe/latest/dg/what-is-transcribe.html)。

## 先決條件任務
<a name="transcribe-example-transcription-medical-jobs"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)
如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)

## 啟動 Amazon Transcribe 醫療轉錄任務
<a name="transcribe-start-medical-transcription"></a>

此範例示範如何使用 啟動 Amazon Transcribe 醫療轉錄任務 適用於 JavaScript 的 AWS SDK。如需詳細資訊，請參閱 [startMedicalTranscriptionJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartMedicalTranscriptionJobCommand/)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`transcribeClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Transcribe 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import  { TranscribeClient }  from  "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Transcribe service object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js)範例程式碼。

以檔名 `transcribe-create-medical-job.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。建立參數物件，指定必要的參數。使用 `StartMedicalTranscriptionJobCommand`命令啟動醫療任務。

**注意**  
將 *MEDICAL\$1JOB\$1NAME* 取代為醫療轉錄任務的名稱。針對 *OUTPUT\$1BUCKET\$1NAME*，指定儲存輸出的 Amazon S3 儲存貯體。針對 *JOB\$1TYPE*，指定任務類型。針對 *SOURCE\$1LOCATION*，指定來源檔案的位置。針對 *SOURCE\$1FILE\$1LOCATION*，指定輸入媒體檔案的位置。

```
// Import the required AWS SDK clients and commands for Node.js
import { StartMedicalTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  MedicalTranscriptionJobName: "MEDICAL_JOB_NAME", // Required
  OutputBucketName: "OUTPUT_BUCKET_NAME", // Required
  Specialty: "PRIMARYCARE", // Required. Possible values are 'PRIMARYCARE'
  Type: "JOB_TYPE", // Required. Possible values are 'CONVERSATION' and 'DICTATION'
  LanguageCode: "LANGUAGE_CODE", // For example, 'en-US'
  MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav'
  Media: {
    MediaFileUri: "SOURCE_FILE_LOCATION",
    // The S3 object location of the input media file. The URI must be in the same region
    // as the API endpoint that you are calling.For example,
    // "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav"
  },
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new StartMedicalTranscriptionJobCommand(params),
    );
    console.log("Success - put", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node transcribe-create-medical-job.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_create_medical_job.js)找到這個範本程式碼。

## 列出 Amazon Transcribe 醫療任務
<a name="transcribe-list-medical-jobs"></a>

此範例說明如何使用 列出 Amazon Transcribe 轉錄任務 適用於 JavaScript 的 AWS SDK。如需詳細資訊，請參閱 [ListTranscriptionMedicalJobsCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListMedicalTranscriptionJobsCommand/)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`transcribeClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Transcribe 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js)範例程式碼。

以檔名 `transcribe-list-medical-jobs.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。使用必要的參數建立參數物件，並使用 `ListMedicalTranscriptionJobsCommand`命令列出醫療任務。

**注意**  
將 *KEYWORD* 取代為傳回任務名稱必須包含的關鍵字。

```
// Import the required AWS SDK clients and commands for Node.js

import { ListMedicalTranscriptionJobsCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  JobNameContains: "KEYWORD", // Returns only transcription job names containing this string
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new ListMedicalTranscriptionJobsCommand(params),
    );
    console.log("Success", data.MedicalTranscriptionJobName);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node transcribe-list-medical-jobs.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_list_medical_jobs.js)找到這個範本程式碼。

## 刪除 Amazon Transcribe 醫療任務
<a name="transcribe-delete-medical-job"></a>

此範例說明如何使用 刪除 Amazon Transcribe 轉錄任務 適用於 JavaScript 的 AWS SDK。如需選用的詳細資訊，請參閱 [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteMedicalTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteMedicalTranscriptionJobCommand/)。

建立`libs`目錄，並建立檔案名稱為 的 Node.js 模組`transcribeClient.js`。複製下面的程式碼並將其貼入其中，這會建立 Amazon Transcribe 用戶端物件。將 *REGION* 取代為您的 AWS 區域。

```
import  { TranscribeClient }  from  "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Transcribe service object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

您可以在 [ GitHub 上找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js)範例程式碼。

以檔名 `transcribe-delete-job.js` 建立一個 Node.js 模組。請務必如先前所示設定軟體開發套件，包括安裝所需的用戶端和套件。使用必要的參數建立參數物件，並使用 `DeleteMedicalJobCommand`命令刪除醫療任務。

**注意**  
將 *JOB\$1NAME* 取代為要刪除的任務名稱。

```
// Import the required AWS SDK clients and commands for Node.js
import { DeleteMedicalTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  MedicalTranscriptionJobName: "MEDICAL_JOB_NAME", // For example, 'medical_transciption_demo'
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new DeleteMedicalTranscriptionJobCommand(params),
    );
    console.log("Success - deleted");
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

若要執行範例，請在命令提示中輸入以下內容。

```
node transcribe-delete-medical-job.js
```

您可以在 [GitHub 上](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_delete_medical_job.js)找到這個範本程式碼。

# 在 Amazon EC2 執行個體上設定 Node.js
<a name="setting-up-node-on-ec2-instance"></a>

搭配適用於 JavaScript 的 SDK 使用 Node.js 的常見案例是在 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體上設定和執行 Node.js Web 應用程式。在本教學課程中，您將建立 Linux 執行個體、使用 SSH 與其連線，接著在該執行個體上安裝 Node.js 並予以執行。

## 先決條件
<a name="setting-up-node-on-ec2-instance.prerequisites"></a>

本教學課程假設您已啟動 Linux 執行個體，其公有 DNS 名稱可從網際網路連線，且您可以使用 SSH 連線。如需如何執行此動作的詳細資訊，請參閱 *Amazon EC2 使用者指南*中的[步驟 1：啟動執行個體](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#ec2-launch-instance)。

**重要**  
啟動新的 **Amazon EC2 執行個體時，請使用 Amazon Linux 2023** Amazon EC2 Machine Image (AMI)。

您還必須先設定安全群組，允許 `SSH` (連接埠 22)、` HTTP` (連接埠 80) 和 `HTTPS` (連接埠 443) 連線。如需這些先決條件的詳細資訊，請參閱《[Amazon EC2 使用者指南》中的使用 Amazon EC2 設定](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html) 。 *Amazon EC2 *

## 程序
<a name="setting-up-node-on-ec2-instance-procedure"></a>

下列程序可協助您在 Amazon Linux 執行個體上安裝 Node.js。您可以使用此伺服器來託管 Node.js Web 應用程式。

**在 Linux 執行個體上設定 Node.js**

1. 以 `ec2-user` 的身分使用 SSH 連線至 Linux 執行個體。

1. 在命令列中輸入以下內容來安裝節點版本管理員 (`nvm`)。
**警告**  
AWS 不會控制下列程式碼。在您執行前，請務必驗證其真確性及完整性。您可以在這裡找到與此程式碼的更多相關資訊：[nvm](https://github.com/nvm-sh/nvm/blob/master/README.md) GitHub 儲存庫。

   ```
   curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
   ```

   我們將使用 安裝 Node.js`nvm`，因為 `nvm`可以安裝多個版本的 Node.js，並允許您在它們之間切換。

1. `nvm` 在命令列輸入以下內容以載入。

   ```
   source ~/.bashrc
   ```

1. 在命令列輸入以下內容，使用 nvm 安裝最新的 Node.js LTS 版本。

   ```
   nvm install --lts
   ```

   安裝 Node.js 也會安裝 Node Package Manager (`npm`)，以便您可以視需要安裝其他模組。

1. 在命令列中輸入以下指令，測試安裝的 Node.js 是否能正常運作。

   ```
   node -e "console.log('Running Node.js ' + process.version)"
   ```

   這會顯示下列訊息，以指出正在執行的 Node.js 版本。

    `Running Node.js VERSION` 

**注意**  
節點安裝僅適用於目前的 Amazon EC2 工作階段。如果您重新啟動 CLI 工作階段，則需要再次使用 nvm 來啟用已安裝的節點版本。如果執行個體終止，您需要再次安裝節點。另一種方法是在您擁有要保留的組態後，建立 Amazon EC2 執行個體的 Amazon Machine Image (AMI)，如下列主題所述。

## 建立 Amazon Machine Image (AMI)
<a name="setting-up-node-on-ec2-instance-create-image"></a>

在 Amazon EC2 執行個體上安裝 Node.js 之後，您可以從該執行個體建立 Amazon Machine Image (AMI)。建立 AMI 可讓您輕鬆地使用相同的 Node.js 安裝佈建多個 Amazon EC2 執行個體。如需從現有執行個體建立 AMI 的詳細資訊，請參閱《*Amazon EC2 使用者指南*》中的[建立 amazon EBS 支援的 Linux AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html)。

## 相關資源
<a name="setting-up-node-on-ec2-instance-related-resource"></a>

如需本主題所用命令和軟體的詳細資訊，請參閱下列網頁：
+ 節點版本管理員 (`nvm`) –—請參閱 [ GitHub 上的 nvm 儲存](https://github.com/creationix/nvm)庫。
+ Node Package Manager (`npm`) –—請參閱 [npm 網站](https://www.npmjs.com)。

# 使用 API Gateway 叫用 Lambda
<a name="api-gateway-invoking-lambda-example"></a>

您可以使用 Amazon API Gateway 叫用 Lambda 函數，這是一種大規模建立、發佈、維護、監控和保護 REST、HTTP 和 WebSocket APIs AWS 的服務。API 開發人員可以建立 APIs 來存取 AWS 或其他 Web 服務，以及存放在 AWS 雲端的資料。身為 API Gateway 開發人員，您可以建立 APIs以用於您自己的用戶端應用程式。如需詳細資訊，請參閱[什麼是 Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html)。

AWS Lambda 是一種運算服務，可讓您執行程式碼，而無需佈建或管理伺服器。您可以使用各種程式設計語言建立 Lambda 函數。如需 的詳細資訊 AWS Lambda，請參閱[什麼是 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 。

在此範例中，您會使用 Lambda JavaScript 執行時期 API 建立 Lambda 函式。此範例會叫用不同的 AWS 服務來執行特定的使用案例。例如，假設組織傳送行動文字訊息給在一年週年紀念日恭喜他們的員工，如下圖所示。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picPhone.png)


此範例大約需要 20 分鐘才能完成。

此範例說明如何使用 JavaScript 邏輯來建立執行此使用案例的解決方案。例如，您將了解如何讀取資料庫，以判斷哪些員工已達到一週年的日期、如何處理資料，以及使用 Lambda 函數傳送文字訊息。然後，您將了解如何使用 API Gateway 來使用 Rest 端點叫用此 AWS Lambda 函數。例如，您可以使用此 curl 命令叫用 Lambda 函數：

```
curl -XGET "https://xxxxqjko1o3.execute-api.us-east-1.amazonaws.com/cronstage/employee" 
```

本 AWS 教學課程使用名為 Employee 的 Amazon DynamoDB 資料表，其中包含這些欄位。
+ **id** - 資料表的主索引鍵。
+ **firstName** - 員工的名字。
+ **電話** - 員工的電話號碼。
+ **startDate** - 員工的開始日期。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/pic00.png)


**重要**  
完成成本：本文件中包含 AWS 的服務包含在 AWS 免費方案中。不過，在完成此範例後，請務必終止所有資源，以確保不會向您收費。

**若要建置應用程式：**

1. [完成先決條件 ](#api-gateway-invoking-lambda-provision-resources)

1. [建立 AWS 資源 ](#api-gateway-invoking-lambda-provision-resources)

1. [準備瀏覽器指令碼 ](#api-gateway-invoking-lambda-browser-script)

1. [建立和上傳 Lambda 函數 ](#api-gateway-invoking-lambda-browser-script)

1. [部署 Lambda 函數 ](#api-gateway-invoking-lambda-deploy-function)

1. [執行應用程式](#api-gateway-invoking-lambda-run)

1. [刪除資源](#api-gateway-invoking-lambda-destroy)

## 先決條件任務
<a name="api-gateway-invoking-lambda-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-api-gateway/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

## 建立 AWS 資源
<a name="api-gateway-invoking-lambda-provision-resources"></a>

本教學課程需要下列資源：
+ 名為 的 Amazon DynamoDB 資料表`Employee`，具有名為 的索引鍵`Id`和上圖中顯示的欄位。請務必輸入正確的資料，包括您要用來測試此使用案例的有效行動電話。如需詳細資訊，請參閱[建立資料表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)。
+ 具有連接許可的 IAM 角色，可執行 Lambda 函數。
+ 用於託管 Lambda 函數的 Amazon S3 儲存貯體。

您可以手動建立這些資源，但建議您 CloudFormation 如本教學所述，使用 佈建這些資源。

### 使用 建立 AWS 資源 CloudFormation
<a name="api-gateway-invoking-lambda-resources-cli"></a>

CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署。如需 的詳細資訊 CloudFormation，請參閱[AWS CloudFormation 《 使用者指南》](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)。

若要使用 建立 CloudFormation 堆疊 AWS CLI：

1. 在 [AWS CLI 使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)中安裝和設定 AWS CLI 下列指示。

1. 在專案資料夾的`setup.yaml`根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/setup.yaml)內容複製到其中。
**注意**  
 CloudFormation 範本是使用 [ GitHub 上此處](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk/lambda_using_api_gateway)提供的 AWS CDK 產生。如需 的詳細資訊 AWS CDK，請參閱 [AWS Cloud Development Kit (AWS CDK) 開發人員指南](https://docs.aws.amazon.com/cdk/latest/guide/)。

1. 從命令列執行下列命令，將 *STACK\$1NAME* 取代為堆疊的唯一名稱。
**重要**  
堆疊名稱在 AWS 區域和 AWS 帳戶中必須是唯一的。您最多可以指定 128 個字元，且允許使用數字和連字號。

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   如需`create-stack`命令參數的詳細資訊，請參閱 [AWS CLI 命令參考指南](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html)和 [CloudFormation 使用者指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)。

1. 接著，依照程序 填入資料表[填入資料表](#api-gateway-invoking-lambda-resources-create-table)。

### 填入資料表
<a name="api-gateway-invoking-lambda-resources-create-table"></a>

若要填入資料表，請先建立名為 的目錄`libs`，並在其中建立名為 的檔案`dynamoClient.js`，並將以下內容貼入其中。

```
const { DynamoDBClient } = require ( "@aws-sdk/client-dynamodb" );
// Set the AWS Region.
const REGION = "REGION"; // e.g. "us-east-1"
 // Create an Amazon Lambda service client object.
const dynamoClient = new DynamoDBClient({region:REGION});
module.exports = { dynamoClient };
```

 此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/dynamoClient.js)。

接著，`populate-table.js`在專案資料夾的根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js)內容複製到其中。對於其中一個項目，請將 `phone` 屬性的值取代為 E.164 格式的有效行動電話號碼，並將 的值`startDate`取代為今天的日期。

從命令列執行下列命令。

```
node populate-table.js
```

```
const { BatchWriteItemCommand } = require ( "aws-sdk/client-dynamodb" );
const {dynamoClient} = require ( "./libs/dynamoClient" );

// Set the parameters.
export const params = {
  RequestItems: {
    Employees: [
      {
        PutRequest: {
          Item: {
            id: { N: "1" },
            firstName: { S: "Bob" },
            phone: { N: "155555555555654" },
            startDate: { S: "2019-12-20" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "2" },
            firstName: { S: "Xing" },
            phone: { N: "155555555555653" },
            startDate: { S: "2019-12-17" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "55" },
            firstName: { S: "Harriette" },
            phone: { N: "155555555555652" },
            startDate: { S: "2019-12-19" },
          },
        },
      },
    ],
  },
};

export const run = async () => {
  try {
    const data = await dbclient.send(new BatchWriteItemCommand(params));
    console.log("Success", data);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

 此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js)。

## 建立 AWS Lambda 函數
<a name="api-gateway-invoking-lambda-browser-script"></a>

### 設定軟體開發套件
<a name="api-gateway-invoking-lambda-configure-sdk"></a>

在 `libs`目錄中，建立名為 `snsClient.js`和 的檔案`lambdaClient.js`，並將以下內容分別貼到這些檔案中。

```
const { SNSClient } = require("@aws-sdk/client-sns");
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon SNS service client object.
const snsClient = new SNSClient({ region: REGION });
module.exports = { snsClient };
```

 將 *REGION* 取代為 AWS 區域。此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/snsClient.js)。

```
const { LambdaClient } = require("@aws-sdk/client-lambda");
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Lambda service client object.
const lambdaClient = new LambdaClient({ region: REGION });
module.exports = { lambdaClient };
```

將 *REGION* 取代為 AWS 區域。此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/lambdaClient.js)。

首先，匯入必要的 適用於 JavaScript 的 AWS SDK (v3) 模組和命令。然後計算今天的日期，並將其指派給參數。第三，建立 的參數`ScanCommand`。將 *TABLE\$1NAME* 取代為您在此範例的 [建立 AWS 資源](#api-gateway-invoking-lambda-provision-resources)區段中建立的資料表名稱。

下列程式碼片段說明此步驟。(如需完整範例，請參閱[綁定 Lambda 函數](#api-gateway-invoking-lambda-full)。)

```
const { ScanCommand } = require("@aws-sdk/client-dynamodb");
const { PublishCommand } = require("@aws-sdk/client-sns");
const { snsClient } = require("./libs/snsClient");
const { dynamoClient } = require("./libs/dynamoClient");

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = `${yyyy}-${mm}-${dd}`;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which are the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "Employees",
};
```

### 掃描 DynamoDB 資料表
<a name="api-gateway-invoking-lambda-scan-table"></a>

首先，建立名為 的非同步/等待函數`sendText`，以使用 Amazon SNS 發佈文字訊息`PublishCommand`。然後，新增`try`區塊模式來掃描 DynamoDB 資料表，尋找今天工作週年紀念的員工，然後呼叫 `sendText`函數來傳送文字訊息給這些員工。如果發生錯誤，則會呼叫 `catch`區塊。

下列程式碼片段說明此步驟。(如需完整範例，請參閱[綁定 Lambda 函數](#api-gateway-invoking-lambda-full)。)

```
// Helper function to send message using Amazon SNS.
exports.handler = async () => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      await snsClient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to identify employees with work anniversary today.
    const data = await dynamoClient.send(new ScanCommand(params));
    for (const element of data.Items) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message: `Hi ${element.firstName.S}; congratulations on your work anniversary!`,
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    }
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

### 綁定 Lambda 函數
<a name="api-gateway-invoking-lambda-full"></a>

本主題說明如何將此範例的 `mylambdafunction.ts`和必要 適用於 JavaScript 的 AWS SDK 模組綁定到稱為 的綁定檔案中`index.js`。

1. 如果您尚未安裝，請遵循此範例[先決條件任務](#api-gateway-invoking-lambda-prerequisites)的 來安裝 Webpack。
**注意**  
如需 *Webpack* 的詳細資訊，請參閱 [使用 Webpack 綁定應用程式](webpack.md)。

1. 在命令列中執行下列命令，將此範例的 JavaScript 綁定到名為 `<index.js>` 的檔案：

   ```
   webpack mylambdafunction.ts --mode development --target node --devtool false --output-library-target umd -o index.js
   ```
**重要**  
請注意，輸出名為 `index.js`。這是因為 Lambda 函數必須有`index.js`處理常式才能運作。

1. 將綁定輸出檔案 壓縮`index.js`為名為 的 ZIP 檔案`mylambdafunction.zip`。

1. `mylambdafunction.zip` 上傳至您在本教學[建立 AWS 資源](#api-gateway-invoking-lambda-provision-resources)課程主題中建立的 Amazon S3 儲存貯體。

## 部署 Lambda 函數。
<a name="api-gateway-invoking-lambda-deploy-function"></a>

在您專案的根目錄中，建立 `lambda-function-setup.ts` 檔案，並將以下內容貼入其中。

將 *BUCKET\$1NAME* 取代為您上傳 Lambda 函數 ZIP 版本的 Amazon S3 儲存貯體名稱。以您 Lambda 函數的 ZIP 版本名稱取代 *ZIP\$1FILE\$1NAME*。將 *ROLE* 取代為您在本教學[建立 AWS 資源](#api-gateway-invoking-lambda-provision-resources)課程中建立之 IAM 角色的 Amazon Resource Number (ARN)。將 *LAMBDA\$1FUNCTION\$1NAME* 取代為 Lambda 函數的名稱。

```
// Load the required Lambda client and commands.
const {
  CreateFunctionCommand
} = require ( "@aws-sdk/client-lambda" );
const { lambdaClient} = require ( "./libs/lambdaClient.js );

// Set the parameters.
const params = {
  Code: {
    S3Bucket: "BUCKET_NAME", // BUCKET_NAME
    S3Key: "ZIP_FILE_NAME", // ZIP_FILE_NAME
  },
  FunctionName: "LAMBDA_FUNCTION_NAME",
  Handler: "index.handler",
  Role: "IAM_ROLE_ARN", // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
  Runtime: "nodejs12.x",
  Description:
    "Scans a DynamoDB table of employee details and using Amazon Simple Notification Services (Amazon SNS) to " +
    "send employees an email on each anniversary of their start-date.",
};

const run = async () => {
  try {
    const data = await lambdaClient.send(new CreateFunctionCommand(params));
    console.log("Success", data); // successful response
  } catch (err) {
    console.log("Error", err); // an error occurred
  }
};
run();
```

在命令列中輸入以下內容以部署 Lambda 函數。

```
node lambda-function-setup.ts
```

此程式碼範例可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/lambda-function-setup.js)。

## 設定 API Gateway 以叫用 Lambda 函數
<a name="api-gateway-invoking-lambda-run"></a>

**若要建置應用程式：**

1. [建立其餘 API](#api-gateway-invoking-lambda-run-create)

1. [測試 API Gateway 方法](#api-gateway-invoking-lambda-run-test)

1. [部署 API Gateway 方法](#api-gateway-invoking-lambda-run-deploy)

### 建立其餘 API
<a name="api-gateway-invoking-lambda-run-create"></a>

您可以使用 API Gateway 主控台來建立 Lambda 函數的靜態端點。完成後，您就可以使用靜態呼叫叫用 Lambda 函數。



1. 登入 [Amazon API Gateway 主控台](https://console.aws.amazon.com/apigateway)。

1. 在 Rest API 下，選擇**建置**。

1. 選取**新增 API**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/PicNewAPI.png)

1. 指定**員工**做為 API 名稱，並提供描述。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picEmployeeAPI.png)

1. 選擇**建立 API**。

1. 在**員工**區段下選擇**資源**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picResources.png)

1. 在名稱欄位中，指定**員工**。

1. 選擇 **Create Resource (建立資源)**。

1. 從**動作**下拉式清單中，選擇**建立資源**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picCreateResources.png)

1. 選擇 **/employees**，從**動作**中選取**建立方法**，然後從 **/employees** 下方的下拉式功能表中選取 **GET**。選擇核取記號圖示。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picGet.png)

1. 選擇 **Lambda 函數**，然後輸入 **mylambdafunction** 做為 Lambda 函數名稱。選擇**儲存**。

### 測試 API Gateway 方法
<a name="api-gateway-invoking-lambda-run-test"></a>

在教學課程中，您可以測試叫用 **mylambdafunction** Lambda 函數的 API Gateway 方法。若要測試 方法，請選擇**測試**，如下圖所示。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picTest.png)


叫用 Lambda 函數後，您可以檢視日誌檔案以查看成功訊息。

### 部署 API Gateway 方法
<a name="api-gateway-invoking-lambda-run-deploy"></a>

測試成功後，您可以從 [Amazon API Gateway 主控台](https://console.aws.amazon.com/apigateway)部署 方法。

1. 選擇**取得**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picGetDeploy.png)

1. 從**動作**下拉式清單中，選取**部署 API**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picDeployMethod.png)

1. 填寫**部署 API** 表單，然後選擇**部署**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picDeployMethod.png)

1.  選擇 **Save Changes** (儲存變更)。

1.  再次選擇**取得**，並注意 URL 變更。這是您可以用來叫用 Lambda 函數的叫用 URL。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picURL2.png)

## 刪除資源
<a name="api-gateway-invoking-lambda-destroy"></a>

恭喜您！您已使用 透過 Amazon API Gateway 叫用 Lambda 函數 適用於 JavaScript 的 AWS SDK。如本教學課程開頭所述，請務必在進行本教學課程時終止您建立的所有資源，以確保不會向您收費。您可以刪除在本教學[建立 AWS 資源](#api-gateway-invoking-lambda-provision-resources)課程主題中建立的 CloudFormation 堆疊來執行此操作，如下所示：

1. [CloudFormation 在 AWS 管理主控台中]( https://console.aws.amazon.com/cloudformation/home)開啟 。

1. 開啟**堆疊**頁面，然後選取堆疊。

1. 選擇**刪除**。

# 建立排程事件以執行 AWS Lambda 函數
<a name="scheduled-events-invoking-lambda-example"></a>

您可以使用 Amazon CloudWatch Event 建立叫用 AWS Lambda 函數的排程事件。您可以設定 CloudWatch Event 使用 Cron 表達式來排程何時叫用 Lambda 函數。例如，您可以排程 CloudWatch 事件，以在每個工作日叫用 Lambda 函數。

AWS Lambda 是一種運算服務，可讓您執行程式碼，而無需佈建或管理伺服器。您可以使用各種程式設計語言建立 Lambda 函數。如需 的詳細資訊 AWS Lambda，請參閱[什麼是 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 。

在本教學課程中，您會使用 Lambda JavaScript 執行時間 API 來建立 Lambda 函數。此範例會叫用不同的 AWS 服務來執行特定的使用案例。例如，假設組織傳送行動文字訊息給在一年週年紀念日恭喜他們的員工，如下圖所示。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picPhone.png)


此教學課程需約 20 分鐘完成。

本教學課程說明如何使用 JavaScript 邏輯來建立執行此使用案例的解決方案。例如，您將了解如何讀取資料庫，以判斷哪些員工已達到一週年的日期、如何處理資料，以及使用 Lambda 函數傳送文字訊息。然後，您將了解如何使用 Cron 表達式，在每個工作日叫用 Lambda 函數。

本 AWS 教學課程使用名為 Employee 的 Amazon DynamoDB 資料表，其中包含這些欄位。
+ **id** - 資料表的主索引鍵。
+ **firstName** - 員工的名字。
+ **電話** - 員工的電話號碼。
+ **startDate** - 員工的開始日期。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/pic00.png)


**重要**  
完成成本：本文件中包含 AWS 的服務包含在 AWS 免費方案中。不過，在完成本教學課程後，請務必終止所有資源，以確保不會向您收費。

**若要建置應用程式：**

1. [完成先決條件 ](#scheduled-events-invoking-lambda-provision-resources)

1. [建立 AWS 資源 ](#scheduled-events-invoking-lambda-provision-resources)

1. [準備瀏覽器指令碼 ](#scheduled-events-invoking-lambda-browser-script)

1. [建立和上傳 Lambda 函數 ](#scheduled-events-invoking-lambda-browser-script)

1. [部署 Lambda 函數 ](#scheduled-events-invoking-lambda-deploy-function)

1. [執行應用程式](#scheduled-events-invoking-lambda-run)

1. [刪除資源](#scheduled-events-invoking-lambda-destroy)

## 先決條件任務
<a name="scheduled-events-invoking-lambda-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node.js TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lex-bot/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

## 建立 AWS 資源
<a name="scheduled-events-invoking-lambda-provision-resources"></a>

本教學課程需要下列資源。
+ 名為 **Employee** 的 Amazon DynamoDB 資料表，其索引鍵名為 **ID**，欄位如上圖所示。請務必輸入正確的資料，包括您要用來測試此使用案例的有效行動電話。如需詳細資訊，請參閱[建立資料表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)。
+ 具有連接許可的 IAM 角色，可執行 Lambda 函數。
+ 用於託管 Lambda 函數的 Amazon S3 儲存貯體。

您可以手動建立這些資源，但建議您 CloudFormation 如本教學所述，使用 佈建這些資源。

### 使用 建立 AWS 資源 CloudFormation
<a name="scheduled-events-invoking-lambda-resources-cli"></a>

CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署。如需 的詳細資訊 CloudFormation，請參閱[AWS CloudFormation 《 使用者指南》](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)。

若要使用 建立 CloudFormation 堆疊 AWS CLI：

1. 在 [AWS CLI 使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)中安裝和設定 AWS CLI 下列指示。

1. 在專案資料夾的`setup.yaml`根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/setup.yaml)內容複製到其中。
**注意**  
 CloudFormation 範本是使用 [ GitHub 上此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/resources/cdk/lambda_using_scheduled_events)提供的 AWS CDK 產生。如需 的詳細資訊 AWS CDK，請參閱 [AWS Cloud Development Kit (AWS CDK) 開發人員指南](https://docs.aws.amazon.com/cdk/latest/guide/)。

1. 從命令列執行下列命令，將 *STACK\$1NAME* 取代為堆疊的唯一名稱。
**重要**  
堆疊名稱在 AWS 區域和 AWS 帳戶中必須是唯一的。您最多可以指定 128 個字元，且允許使用數字和連字號。

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   如需`create-stack`命令參數的詳細資訊，請參閱 [AWS CLI 命令參考指南](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html)和 [CloudFormation 使用者指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)。

   透過在 CloudFormation 儀表板上開啟堆疊，然後選擇資源索引標籤，在主控台中檢視**資源**清單。教學課程需要這些項目。

1. 建立堆疊時，請使用 適用於 JavaScript 的 AWS SDK 填入 DynamoDB 資料表，如 中所述[填入 DynamoDB 資料表](#scheduled-events-invoking-lambda-resources-create-table)。

### 填入 DynamoDB 資料表
<a name="scheduled-events-invoking-lambda-resources-create-table"></a>

若要填入資料表，請先建立名為 的目錄`libs`，並在其中建立名為 的檔案`dynamoClient.js`，並將以下內容貼入其中。

```
const { DynamoDBClient } = require( "@aws-sdk/client-dynamodb" );
// Set the AWS Region.
const REGION = "REGION"; // e.g. "us-east-1"
// Create an Amazon DynamoDB service client object.
const dynamoClient = new DynamoDBClient({region:REGION});
module.exports = { dynamoClient };
```

 此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js)。

接著，`populate-table.js`在專案資料夾的根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js)內容複製到其中。對於其中一個項目，請將 `phone` 屬性的值取代為 E.164 格式的有效行動電話號碼，並將 的值`startDate`取代為今天的日期。

從命令列執行下列命令。

```
node populate-table.js
```

```
const {
BatchWriteItemCommand } = require( "aws-sdk/client-dynamodb" );
const {dynamoClient} = require(  "./libs/dynamoClient" );
// Set the parameters.
const params = {
  RequestItems: {
    Employees: [
      {
        PutRequest: {
          Item: {
            id: { N: "1" },
            firstName: { S: "Bob" },
            phone: { N: "155555555555654" },
            startDate: { S: "2019-12-20" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "2" },
            firstName: { S: "Xing" },
            phone: { N: "155555555555653" },
            startDate: { S: "2019-12-17" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "55" },
            firstName: { S: "Harriette" },
            phone: { N: "155555555555652" },
            startDate: { S: "2019-12-19" },
          },
        },
      },
    ],
  },
};

export const run = async () => {
  try {
    const data = await dbclient.send(new BatchWriteItemCommand(params));
    console.log("Success", data);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

 此程式碼可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js)。

## 建立 AWS Lambda 函數
<a name="scheduled-events-invoking-lambda-browser-script"></a>

### 設定軟體開發套件
<a name="scheduled-events-invoking-lambda-configure-sdk"></a>

首先匯入 required 適用於 JavaScript 的 AWS SDK (v3) 模組和命令： `DynamoDBClient` 和 DynamoDB `ScanCommand`、 和 `SNSClient`以及 Amazon SNS `PublishCommand`命令。將 *REGION* 取代為 AWS 區域。然後計算今天的日期，並將其指派給參數。然後使用您在此範例的 [建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)區段中建立的資料表名稱來建立 `ScanCommand`.Replace *TABLE\$1NAME* 的參數。

下列程式碼片段說明此步驟。(如需完整範例，請參閱[綁定 Lambda 函數](#scheduled-events-invoking-lambda-full)。)

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};
```

### 掃描 DynamoDB 資料表
<a name="scheduled-events-invoking-lambda-scan-table"></a>

首先建立名為 的非同步/等待函數`sendText`，以使用 Amazon SNS 發佈文字訊息`PublishCommand`。然後，新增`try`區塊模式來掃描 DynamoDB 資料表，尋找今天工作週年紀念的員工，然後呼叫 `sendText`函數來傳送文字訊息給這些員工。如果發生錯誤，則會呼叫 `catch`區塊。

下列程式碼片段說明此步驟。(如需完整範例，請參閱[綁定 Lambda 函數](#scheduled-events-invoking-lambda-full)。)

```
exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

### 綁定 Lambda 函數
<a name="scheduled-events-invoking-lambda-full"></a>

本主題說明如何將此範例的 `mylambdafunction.js`和必要 適用於 JavaScript 的 AWS SDK 模組綁定到稱為 的綁定檔案中`index.js`。

1. 如果您尚未安裝，請遵循此範例[先決條件任務](#scheduled-events-invoking-lambda-prerequisites)的 來安裝 Webpack。
**注意**  
如需 *Webpack *的相關資訊，請參閱 [使用 Webpack 綁定應用程式](webpack.md)。

1. 在命令列中執行下列命令，將此範例的 JavaScript 綁定到名為 `<index.js>` 的檔案：

   ```
   webpack mylamdbafunction.js --mode development --target node --devtool false --output-library-target umd -o index.js
   ```
**重要**  
請注意，輸出名為 `index.js`。這是因為 Lambda 函數必須有`index.js`處理常式才能運作。

1. 將綁定輸出檔案 壓縮`index.js`為名為 的 ZIP 檔案`my-lambda-function.zip`。

1. `mylambdafunction.zip` 上傳至您在本教學[建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)課程主題中建立的 Amazon S3 儲存貯體。

以下是 的完整瀏覽器指令碼程式碼`mylambdafunction.js`。

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};

// Create the client service objects.
const dbclient = new DynamoDBClient({ region: REGION });
const snsclient = new SNSClient({ region: REGION });

exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

## 部署 Lambda 函數。
<a name="scheduled-events-invoking-lambda-deploy-function"></a>

在您專案的根目錄中，建立 `lambda-function-setup.js` 檔案，並將以下內容貼入其中。

將 *BUCKET\$1NAME* 取代為您上傳 Lambda 函數 ZIP 版本的 Amazon S3 儲存貯體名稱。以您 Lambda 函數的 ZIP 版本名稱取代 *ZIP\$1FILE\$1NAME*。將 *IAM\$1ROLE\$1ARN* 取代為您在本教學[建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)課程中建立之 IAM 角色的 Amazon Resource Number (ARN)。將 *LAMBDA\$1FUNCTION\$1NAME* 取代為 Lambda 函數的名稱。

```
// Load the required Lambda client and commands.
const {
   CreateFunctionCommand,
} = require("@aws-sdk/client-lambda");
const {
   lambdaClient
} = require("..libs/lambdaClient.js");

// Instantiate an Lambda client service object.
const lambda = new LambdaClient({ region: REGION });

// Set the parameters.
const params = {
  Code: {
    S3Bucket: "BUCKET_NAME", // BUCKET_NAME
    S3Key: "ZIP_FILE_NAME", // ZIP_FILE_NAME
  },
  FunctionName: "LAMBDA_FUNCTION_NAME",
  Handler: "index.handler",
  Role: "IAM_ROLE_ARN", // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
  Runtime: "nodejs12.x",
  Description:
    "Scans a DynamoDB table of employee details and using Amazon Simple Notification Services (Amazon SNS) to " +
    "send employees an email the each anniversary of their start-date.",
};

const run = async () => {
  try {
    const data = await lambda.send(new CreateFunctionCommand(params));
    console.log("Success", data); // successful response
  } catch (err) {
    console.log("Error", err); // an error occurred
  }
};
run();
```

在命令列中輸入以下內容以部署 Lambda 函數。

```
node lambda-function-setup.js
```

此程式碼範例可在 [ GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js)。

## 設定 CloudWatch 以叫用 Lambda 函數
<a name="scheduled-events-invoking-lambda-run"></a>

若要設定 CloudWatch 叫用 Lambda 函數：

1. 開啟 Lambda 主控台中的 **Functions (函數) 頁面**。

1. 選擇 Lambda 函數。

1. 在 **Designer (設計工具)** 下，選擇 **Add trigger (新增觸發)**。

1. 將觸發類型設定為 **CloudWatch Events/EventBridge**。

1. 針對規則，選擇**建立新規則**。

1.  填寫規則名稱和規則描述。

1. 針對規則類型，選取**排程表達**式。

1. 在**排程表達**式欄位中，輸入 Cron 表達式。例如，**cron(0 12 ？ \$1 MON-FRI \$1)**。

1. 選擇**新增**。
**注意**  
如需詳細資訊，請參閱[搭配使用 Lambda 與 CloudWatch Events](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents.html)。

## 刪除資源
<a name="scheduled-events-invoking-lambda-destroy"></a>

恭喜您！您已使用 透過 Amazon CloudWatch 排程事件叫用 Lambda 函數 適用於 JavaScript 的 AWS SDK。如本教學課程開頭所述，請務必在進行本教學課程時終止您建立的所有資源，以確保不會向您收費。您可以刪除在本教學[建立 AWS 資源](#scheduled-events-invoking-lambda-provision-resources)課程主題中建立的 CloudFormation 堆疊來執行此操作，如下所示：

1. 開啟 [CloudFormation 主控台]( https://console.aws.amazon.com/cloudformation/home)。

1. 在**堆疊**頁面上，選取堆疊。

1. 選擇**刪除**。

# 建置 Amazon Lex 聊天機器人
<a name="lex-bot-example"></a>

您可以在 Web 應用程式中建立 Amazon Lex 聊天機器人，以吸引網站訪客。Amazon Lex 聊天機器人是與使用者進行線上聊天對話的功能，無需與人員直接聯絡。例如，下圖顯示 Amazon Lex 聊天機器人，可讓使用者參與預訂飯店房間。

![\[Chatbot interface demonstrating a hotel booking conversation with user inputs and bot responses.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/lex_example/chatintro.png)


在本 AWS 教學課程中建立的 Amazon Lex 聊天機器人能夠處理多種語言。例如，說法文的使用者可以輸入法文，並以法文傳回回應。

![\[Chatbot interface demonstrating Amazon Lex integration with French language support.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/lex_example/LanChatBot2.png)


同樣地，使用者可以使用義大利文與 Amazon Lex 聊天機器人通訊。

![\[Chat interface showing Italian language exchange between user and Amazon Lex chatbot.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/lex_example/LanChatBot3.png)


本 AWS 教學課程會引導您建立 Amazon Lex 聊天機器人，並將其整合到 Node.js Web 應用程式。 適用於 JavaScript 的 AWS SDK (v3) 用於叫用 AWS 這些服務：
+ Amazon Lex
+ Amazon Comprehend
+ Amazon Translate

**完成成本：**本文件中包含 AWS 的服務包含在 [AWS 免費方案](https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc)中。

**注意：**請務必在進行本教學課程時終止您建立的所有資源，以確保不會向您收費。

**若要建置應用程式：**

1. [先決條件](#lex-bot-example-prerequisites)

1. [佈建資源](#lex-bot-provision-resources)

1. [建立 Amazon Lex 聊天機器人](#lex-bot-example-create-lex-bot)

1. [建立 HTML](#lex-bot-example-html)

1. [建立瀏覽器指令碼](#lex-bot-example-script)

1. [後續步驟](#lex-bot-example-next-steps)

## 先決條件
<a name="lex-bot-example-prerequisites"></a>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
此範例使用 ECMAScript6 (ES6)。這需要 Node.js 13.x 版或更新版本。若要下載並安裝最新版本的 Node.js，請參閱 [Node.js 下載。](https://nodejs.org/en/download)  
不過，如果您偏好使用 CommonJS 語法，請參閱 [JavaScript ES6/CommonJS 語法](sdk-example-javascript-syntax.md)。

## 建立 AWS 資源
<a name="lex-bot-provision-resources"></a>

本教學課程需要下列資源。
+ 未驗證的 IAM 角色，具有對下列項目的連接許可：
  + Amazon Comprehend
  + Amazon Translate
  + Amazon Lex

您可以手動建立此資源，但我們建議您使用 佈建這些資源， AWS CloudFormation 如本教學所述。

### 使用 建立 AWS 資源 CloudFormation
<a name="lex-bot-example-resources-cli"></a>

CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署。如需 的詳細資訊 CloudFormation，請參閱[AWS CloudFormation 《 使用者指南》](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)。

若要使用 建立 CloudFormation 堆疊 AWS CLI：

1. 在 [AWS CLI 使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)中安裝和設定 AWS CLI 下列指示。

1. 在專案資料夾的`setup.yaml`根目錄中建立名為 的檔案，並將 [ GitHub 上的此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lex-bot/setup.yaml)內容複製到其中。
**注意**  
 CloudFormation 範本是使用 [ GitHub 上此處](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk/lex_bot_example_iam_unauth_role)提供的 AWS CDK 產生。如需 的詳細資訊 AWS CDK，請參閱 [AWS Cloud Development Kit (AWS CDK) 開發人員指南](https://docs.aws.amazon.com/cdk/latest/guide/)。

1. 從命令列執行下列命令，將 *STACK\$1NAME* 取代為堆疊的唯一名稱。
**重要**  
堆疊名稱在 AWS 區域和 AWS 帳戶中必須是唯一的。您最多可以指定 128 個字元，且允許使用數字和連字號。

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   如需`create-stack`命令參數的詳細資訊，請參閱 [AWS CLI 命令參考指南](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html)和 [CloudFormation 使用者指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)。

   若要檢視建立的資源，請開啟 Amazon Lex 主控台，選擇堆疊，然後選取**資源**索引標籤。

## 建立 Amazon Lex 機器人
<a name="lex-bot-example-create-lex-bot"></a>

**重要**  
使用 Amazon Lex 主控台的 V1 來建立機器人。此範例不適用於使用 V2 建立的機器人。

第一步是使用 Amazon Web Services 管理主控台建立 Amazon Lex 聊天機器人。在此範例中，使用 Amazon Lex **BookTrip** 範例。如需詳細資訊，請參閱[預訂行程](https://docs.aws.amazon.com/lex/latest/dg/ex-book-trip.html)。
+ 登入 Amazon Web Services 管理主控台，並在 Amazon Web Services 主控台開啟 Amazon Lex [主控台](https://console.aws.amazon.com/lex/)。
+ 在機器人頁面上，選擇**建立**。
+ 選擇 **BookTrip** 藍圖 （保留預設機器人名稱 **BookTrip**)。  
![\[Interface for creating a chatbot, showing BookTrip sample with conversation flow and components.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/lex_example/pic2.png)
+ 填寫預設設定，然後選擇**建立** （主控台會顯示 **BookTrip** 機器人）。在編輯器索引標籤上，檢閱預先設定意圖的詳細資訊。
+ 在測試視窗中測試機器人。輸入*我想要預訂飯店房間*來開始測試。  
![\[Chat interface showing a hotel booking conversation with a bot asking for the city.\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/lex_example/ChatBotTest.png)
+ 選擇**發佈**並指定別名名稱 （使用 時需要此值 適用於 JavaScript 的 AWS SDK)。

**注意**  
 您需要在 JavaScript 程式碼中參考**機器人名稱**和**機器人別名**。

## 建立 HTML
<a name="lex-bot-example-html"></a>

建立名為 `index.html` 的檔案。將下面的程式碼複製並貼到 `index.html`。此 HTML 參考 `main.js`。這是 index.js 的綁定版本，其中包含必要的 適用於 JavaScript 的 AWS SDK 模組。您將在 中建立此檔案[建立 HTML](#lex-bot-example-html)。 `index.html`也參考 `style.css`，這會新增樣式。

```
<!doctype html>
<head>
  <title>Amazon Lex - Sample Application (BookTrip)</title>
  <link type="text/css" rel="stylesheet" href="style.css" />
</head>

<body>
  <h1 id="title">Amazon Lex - BookTrip</h1>
  <p id="intro">
    This multiple language chatbot shows you how easy it is to incorporate
    <a
      href="https://aws.amazon.com/lex/"
      title="Amazon Lex (product)"
      target="_new"
      >Amazon Lex</a
    >
    into your web apps. Try it out.
  </p>
  <div id="conversation"></div>
  <input
    type="text"
    id="wisdom"
    size="80"
    value=""
    placeholder="J'ai besoin d'une chambre d'hôtel"
  />
  <br />
  <button onclick="createResponse()">Send Text</button>
  <script type="text/javascript" src="./main.js"></script>
</body>
```

此程式碼也可[在 GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk#running-a-cdk-app)。

## 建立瀏覽器指令碼
<a name="lex-bot-example-script"></a>

建立名為 `index.js` 的檔案。將下面的程式碼複製並貼到 中`index.js`。匯入必要的 適用於 JavaScript 的 AWS SDK 模組和命令。為 Amazon Lex、Amazon Comprehend 和 Amazon Translate 建立用戶端。將 *REGION* 取代為 AWS 區域，並將 *IDENTITY\$1POOL\$1ID* 取代為您在 中建立的身分集區的 ID[建立 AWS 資源](#lex-bot-provision-resources)。若要擷取此身分集區 ID，請在 Amazon Cognito 主控台中開啟身分集區，選擇**編輯身分集區**，然後在側邊功能表中選擇**範例程式碼**。身分集區 ID 在主控台中以紅色文字顯示。

首先，建立`libs`目錄建立所需的服務用戶端物件，方法是建立三個檔案 `comprehendClient.js`、 `lexClient.js`和 `translateClient.js`。將下列適當的程式碼貼到每個檔案中，並取代每個檔案中的 *REGION* 和 *IDENTITY\$1POOL\$1ID*。

**注意**  
使用您在 中建立的 Amazon Cognito 身分集區的 ID[使用 建立 AWS 資源 CloudFormation](#lex-bot-example-resources-cli)。

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { ComprehendClient } from "@aws-sdk/client-comprehend";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Comprehend service client object.
const comprehendClient = new ComprehendClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { comprehendClient };
```

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { LexRuntimeServiceClient } from "@aws-sdk/client-lex-runtime-service";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Lex service client object.
const lexClient = new LexRuntimeServiceClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { lexClient };
```

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { TranslateClient } from "@aws-sdk/client-translate";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Translate service client object.
const translateClient = new TranslateClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { translateClient };
```

此程式碼可在 [ GitHub 上取得。](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lex-bot/src/libs)

接著，建立 `index.js` 檔案，並將下面的程式碼貼入其中。

 將 *BOT\$1ALIAS* 和 *BOT\$1NAME* 分別取代為 Amazon Lex 機器人的別名和名稱，並將 *USER\$1ID* 取代為使用者 ID。`createResponse` 非同步函數會執行下列動作：
+ 將使用者輸入的文字帶入瀏覽器，並使用 Amazon Comprehend 來判斷其語言代碼。
+ 使用語言程式碼並使用 Amazon Translate 將文字翻譯為英文。
+ 接受翻譯的文字，並使用 Amazon Lex 產生回應。
+ 將回應發佈至瀏覽器頁面。

```
import { DetectDominantLanguageCommand } from "@aws-sdk/client-comprehend";
import { TranslateTextCommand } from "@aws-sdk/client-translate";
import { PostTextCommand } from "@aws-sdk/client-lex-runtime-service";
import { lexClient } from "./libs/lexClient.js";
import { translateClient } from "./libs/translateClient.js";
import { comprehendClient } from "./libs/comprehendClient.js";

let g_text = "";
// Set the focus to the input box.
document.getElementById("wisdom").focus();

function showRequest() {
  const conversationDiv = document.getElementById("conversation");
  const requestPara = document.createElement("P");
  requestPara.className = "userRequest";
  requestPara.appendChild(document.createTextNode(g_text));
  conversationDiv.appendChild(requestPara);
  conversationDiv.scrollTop = conversationDiv.scrollHeight;
}

function showResponse(lexResponse) {
  const conversationDiv = document.getElementById("conversation");
  const responsePara = document.createElement("P");
  responsePara.className = "lexResponse";

  const lexTextResponse = lexResponse;

  responsePara.appendChild(document.createTextNode(lexTextResponse));
  responsePara.appendChild(document.createElement("br"));
  conversationDiv.appendChild(responsePara);
  conversationDiv.scrollTop = conversationDiv.scrollHeight;
}

function handletext(text) {
  g_text = text;
  const xhr = new XMLHttpRequest();
  xhr.addEventListener("load", loadNewItems, false);
  xhr.open("POST", "../text", true); // A Spring MVC controller
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //necessary
  xhr.send(`text=${text}`);
}

function loadNewItems() {
  showRequest();

  // Re-enable input.
  const wisdomText = document.getElementById("wisdom");
  wisdomText.value = "";
  wisdomText.locked = false;
}

// Respond to user's input.
const createResponse = async () => {
  // Confirm there is text to submit.
  const wisdomText = document.getElementById("wisdom");
  if (wisdomText?.value && wisdomText.value.trim().length > 0) {
    // Disable input to show it is being sent.
    const wisdom = wisdomText.value.trim();
    wisdomText.value = "...";
    wisdomText.locked = true;
    handletext(wisdom);

    const comprehendParams = {
      Text: wisdom,
    };
    try {
      const data = await comprehendClient.send(
        new DetectDominantLanguageCommand(comprehendParams),
      );
      console.log(
        "Success. The language code is: ",
        data.Languages[0].LanguageCode,
      );
      const translateParams = {
        SourceLanguageCode: data.Languages[0].LanguageCode,
        TargetLanguageCode: "en", // For example, "en" for English.
        Text: wisdom,
      };
      try {
        const data = await translateClient.send(
          new TranslateTextCommand(translateParams),
        );
        console.log("Success. Translated text: ", data.TranslatedText);
        const lexParams = {
          botName: "BookTrip",
          botAlias: "mynewalias",
          inputText: data.TranslatedText,
          userId: "chatbot", // For example, 'chatbot-demo'.
        };
        try {
          const data = await lexClient.send(new PostTextCommand(lexParams));
          console.log("Success. Response is: ", data.message);
          const msg = data.message;
          showResponse(msg);
        } catch (err) {
          console.log("Error responding to message. ", err);
        }
      } catch (err) {
        console.log("Error translating text. ", err);
      }
    } catch (err) {
      console.log("Error identifying language. ", err);
    }
  }
};
// Make the function available to the browser.
window.createResponse = createResponse;
```

此程式碼可在 [ GitHub 上取得。](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lex-bot/src/index.html)

現在使用 webpack 將 `index.js`和 適用於 JavaScript 的 AWS SDK 模組綁定到單一檔案 `main.js`。

1. 如果您尚未安裝，請遵循此範例[先決條件](#lex-bot-example-prerequisites)的 來安裝 Webpack。
**注意**  
如需 *Webpack *的相關資訊，請參閱 [使用 Webpack 綁定應用程式](webpack.md)。

1. 在命令列中執行下列命令，將此範例的 JavaScript 綁定到名為 的檔案`main.js`：

   ```
   webpack index.js --mode development --target web --devtool false -o main.js
   ```

## 後續步驟
<a name="lex-bot-example-next-steps"></a>

恭喜您！您已建立使用 Amazon Lex 建立互動式使用者體驗的 Node.js 應用程式。如本教學課程開頭所述，請務必在進行本教學課程時終止您建立的所有資源，以確保不會向您收費。您可以刪除在本教學[建立 AWS 資源](#lex-bot-provision-resources)課程主題中建立的 CloudFormation 堆疊來執行此操作，如下所示：

1. 開啟 [CloudFormation 主控台]( https://console.aws.amazon.com/cloudformation/home)。

1. 在**堆疊**頁面上，選取堆疊。

1. 選擇 **刪除**。

如需 AWS 更多跨服務範例，請參閱[適用於 JavaScript 的 AWS SDK 跨服務範例](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/tutorials.html)。