

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

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

# Node.js 入門
<a name="getting-started-nodejs"></a>

本指南說明如何初始化 NPM 套件、將服務用戶端新增至套件，以及使用 JavaScript 開發套件呼叫服務動作。

## 案例
<a name="getting-started-nodejs-scenario"></a>

**使用執行下列動作的主檔案建立新的 NPM 套件：**
+ 建立 Amazon Simple Storage Service 儲存貯體
+ 將物件放入 Amazon S3 儲存貯體
+ 讀取 Amazon S3 儲存貯體中的物件
+ 確認使用者是否要刪除資源

## 先決條件
<a name="getting-started-nodejs-prerequisites"></a>

您必須先執行下列動作，才能執行範例：
+ 設定您的 SDK 身分驗證。如需詳細資訊，請參閱[使用 進行 SDK 身分驗證 AWS](getting-your-credentials.md)。
+ 使用 [Node.js](https://nodejs.org/en/download) 的 Active LTS 版本進行開發，安裝 Node.js. AWS recommends。

## 步驟 1：設定套件結構並安裝用戶端套件
<a name="getting-started-nodejs-setup-structure"></a>

若要設定套件結構並安裝用戶端套件：

1. 建立新的資料夾`nodegetstarted`以包含套件。

1. 從命令列導覽至新的資料夾。

1. 執行下列命令來建立預設`package.json`檔案：

   ```
   npm init -y
   ```

1. 執行下列命令來安裝 Amazon S3 用戶端套件：

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

1. 將 `"type": "module"`新增至 `package.json` 檔案。這會通知 Node.js 使用現代 ESM 語法。最終看起來`package.json`應該類似以下內容：

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

## 步驟 2：新增必要的匯入和 SDK 程式碼
<a name="getting-started-with-node-js-add-code"></a>

將下列程式碼新增至 `nodegetstarted` 資料夾中名為 `index.js` 的檔案。

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

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

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

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

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

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

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

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

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

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

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

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

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

## 步驟 3：執行範例
<a name="getting-started-with-node-js-run"></a>

**注意**  
請記得登入！如果您使用 IAM Identity Center 進行身分驗證，請記得使用 AWS CLI `aws sso login`命令登入。

1. 執行 `node index.js`。

1. 選擇是否清空並刪除儲存貯體。

1. 如果您未刪除儲存貯體，請務必手動清空並稍後刪除。