

 [AWS SDK for JavaScript V3 API リファレンスガイド](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)では、 AWS SDK for JavaScript バージョン3 (V3) のすべての API オペレーションについて詳しく説明します。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Node.js での開始方法
<a name="getting-started-nodejs"></a>

このガイドでは、NPM パッケージを初期化し、パッケージにサービスクライアントを追加し、JavaScript SDK を使用してサービスアクションを呼び出す方法を説明します。

## シナリオ
<a name="getting-started-nodejs-scenario"></a>

**次の処理を実行するメインファイルを 1 つ含む、新しい NPM パッケージを作成します。**
+ Amazon Simple Storage Service バケットの作成
+ Amazon S3 バケットへのオブジェクトの配置
+ Amazon S3 バケット内のオブジェクトの読み取り
+ ユーザーがリソースを削除したいかどうかの確認

## 前提条件
<a name="getting-started-nodejs-prerequisites"></a>

例を実行するには、次の手順を行います。
+ SDK 認証を設定します。詳細については、「[を使用した SDK 認証 AWS](getting-your-credentials.md)」を参照してください。
+ 開発用の [Node.js](https://nodejs.org/en/download) のアクティブ LTS バージョンを使用して Node.js. AWS recommends をインストールします。

## ステップ 1: パッケージ構造を設定してクライアントパッケージをインストールする
<a name="getting-started-nodejs-setup-structure"></a>

パッケージ構造を設定し、クライアントパッケージをインストールするには、次の手順を実行します。

1. 新しいフォルダ `nodegetstarted` を作成して、パッケージを格納します。

1. コマンドラインから、新しいフォルダに移動します。

1. 次のコマンドを実行して、デフォルト `package.json` ファイルを作成します。

   ```
   npm init -y
   ```

1. 次のコマンドを実行して、Amazon S3 クライアントパッケージをインストールします。

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

1. `"type": "module"` を `package.json` ファイルに追加します。これにより、最新の ESM 構文を使用するように Node.js に指示します。最終的な `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. バケットを削除しない場合は、手動で空にして後で削除してください。