SDK for JavaScript (v3) を使用した Amazon S3 の例 - AWS SDK for JavaScript

AWS SDK for JavaScript V3 API リファレンスガイドでは、 AWS SDK for JavaScript バージョン3 (V3) のすべての API オペレーションについて詳しく説明します。

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

SDK for JavaScript (v3) を使用した Amazon S3 の例

次のコード例は、Amazon S3 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。 Amazon S3

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

開始方法

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; // When no region or credentials are provided, the SDK will use the // region and credentials from the local AWS config. const client = new S3Client({}); export const helloS3 = async () => { const command = new ListBucketsCommand({}); const { Buckets } = await client.send(command); console.log("Buckets: "); console.log(Buckets.map((bucket) => bucket.Name).join("\n")); return Buckets; };
  • API の詳細については、「 API リファレンスListBuckets」の「」を参照してください。 AWS SDK for JavaScript

アクション

次のコード例は、Cross-Origin Resource Sharing (CORS) ルールを S3 バケットに追加する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

CORS ルールを追加します。

import { PutBucketCorsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // By default, Amazon S3 doesn't allow cross-origin requests. Use this command // to explicitly allow cross-origin requests. export const main = async () => { const command = new PutBucketCorsCommand({ Bucket: "test-bucket", CORSConfiguration: { CORSRules: [ { // Allow all headers to be sent to this bucket. AllowedHeaders: ["*"], // Allow only GET and PUT methods to be sent to this bucket. AllowedMethods: ["GET", "PUT"], // Allow only requests from the specified origin. AllowedOrigins: ["https://www.example.com"], // Allow the entity tag (ETag) header to be returned in the response. The ETag header // The entity tag represents a specific version of the object. The ETag reflects // changes only to the contents of an object, not its metadata. ExposeHeaders: ["ETag"], // How long the requesting browser should cache the preflight response. After // this time, the preflight request will have to be made again. MaxAgeSeconds: 3600, }, ], }, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例は、S3 バケットにポリシーを追加する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

ポリシーを追加します。

import { PutBucketPolicyCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new PutBucketPolicyCommand({ Policy: JSON.stringify({ Version: "2012-10-17", Statement: [ { Sid: "AllowGetObject", // Allow this particular user to call GetObject on any object in this bucket. Effect: "Allow", Principal: { AWS: "arn:aws:iam::ACCOUNT-ID:user/USERNAME", }, Action: "s3:GetObject", Resource: "arn:aws:s3:::BUCKET-NAME/*", }, ], }), // Apply the preceding policy to this bucket. Bucket: "BUCKET-NAME", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例では、1 つのバケットから別のバケットに S3 オブジェクトをコピーする方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

オブジェクトをコピーします。

import { S3Client, CopyObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new CopyObjectCommand({ CopySource: "SOURCE_BUCKET/SOURCE_OBJECT_KEY", Bucket: "DESTINATION_BUCKET", Key: "NEW_OBJECT_KEY", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
  • API の詳細については、「 API リファレンスCopyObject」の「」を参照してください。 AWS SDK for JavaScript

次のコード例では、S3 バケットを作成する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケットを作成します。

import { CreateBucketCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new CreateBucketCommand({ // The name of the bucket. Bucket names are unique and have several other constraints. // See https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html Bucket: "bucket-name", }); try { const { Location } = await client.send(command); console.log(`Bucket created with location ${Location}`); } catch (err) { console.error(err); } };

次のコード例は、S3 バケットからポリシーを削除する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケット ポリシーを削除します。

import { DeleteBucketPolicyCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // This will remove the policy from the bucket. export const main = async () => { const command = new DeleteBucketPolicyCommand({ Bucket: "test-bucket", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例では、空の S3 バケットを削除する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケットを削除します。

import { DeleteBucketCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Delete a bucket. export const main = async () => { const command = new DeleteBucketCommand({ Bucket: "test-bucket", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例は、S3 オブジェクトを削除する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

オブジェクトを削除します。

import { DeleteObjectCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new DeleteObjectCommand({ Bucket: "test-bucket", Key: "test-key.txt", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
  • API の詳細については、「 API リファレンスDeleteObject」の「」を参照してください。 AWS SDK for JavaScript

次のコード例では、S3 バケットから複数のオブジェクトを削除する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

複数のオブジェクトを削除します。

import { DeleteObjectsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new DeleteObjectsCommand({ Bucket: "test-bucket", Delete: { Objects: [{ Key: "object1.txt" }, { Key: "object2.txt" }], }, }); try { const { Deleted } = await client.send(command); console.log( `Successfully deleted ${Deleted.length} objects from S3 bucket. Deleted objects:`, ); console.log(Deleted.map((d) => ` • ${d.Key}`).join("\n")); } catch (err) { console.error(err); } };
  • API の詳細については、「 API リファレンスDeleteObjects」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、S3 バケットからウェブサイト設定を削除する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケットからウェブサイト設定を削除します。

import { DeleteBucketWebsiteCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Disable static website hosting on the bucket. export const main = async () => { const command = new DeleteBucketWebsiteCommand({ Bucket: "test-bucket", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例は、S3 バケットの Cross-Origin Resource Sharing (CORS) ルールを取得する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケットの CORS ポリシーを取得します。

import { GetBucketCorsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new GetBucketCorsCommand({ Bucket: "test-bucket", }); try { const { CORSRules } = await client.send(command); CORSRules.forEach((cr, i) => { console.log( `\nCORSRule ${i + 1}`, `\n${"-".repeat(10)}`, `\nAllowedHeaders: ${cr.AllowedHeaders.join(" ")}`, `\nAllowedMethods: ${cr.AllowedMethods.join(" ")}`, `\nAllowedOrigins: ${cr.AllowedOrigins.join(" ")}`, `\nExposeHeaders: ${cr.ExposeHeaders.join(" ")}`, `\nMaxAgeSeconds: ${cr.MaxAgeSeconds}`, ); }); } catch (err) { console.error(err); } };

次のコード例では、S3 バケット内のオブジェクトからデータを読み取る方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

オブジェクトをダウンロードします。

import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new GetObjectCommand({ Bucket: "test-bucket", Key: "hello-s3.txt", }); try { const response = await client.send(command); // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods. const str = await response.Body.transformToString(); console.log(str); } catch (err) { console.error(err); } };

次のコード例は、S3 バケットのアクセスコントロールリスト (ACL) を取得する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

ACL 許可を取得します。

import { GetBucketAclCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new GetBucketAclCommand({ Bucket: "test-bucket", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例は、S3 バケットのポリシーを取得する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケットポリシーを取得します。

import { GetBucketPolicyCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new GetBucketPolicyCommand({ Bucket: "test-bucket", }); try { const { Policy } = await client.send(command); console.log(JSON.parse(Policy)); } catch (err) { console.error(err); } };

次のコード例は、S3 バケットのウェブサイト設定を取得する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

ウェブサイト設定を取得します。

import { GetBucketWebsiteCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new GetBucketWebsiteCommand({ Bucket: "test-bucket", }); try { const { ErrorDocument, IndexDocument } = await client.send(command); console.log( `Your bucket is set up to host a website. It has an error document:`, `${ErrorDocument.Key}, and an index document: ${IndexDocument.Suffix}.`, ); } catch (err) { console.error(err); } };
  • API の詳細については、「 API リファレンスGetBucketWebsite」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、S3 バケットを一覧表示する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケットを一覧表示します。

import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new ListBucketsCommand({}); try { const { Owner, Buckets } = await client.send(command); console.log( `${Owner.DisplayName} owns ${Buckets.length} bucket${ Buckets.length === 1 ? "" : "s" }:`, ); console.log(`${Buckets.map((b) => ` • ${b.Name}`).join("\n")}`); } catch (err) { console.error(err); } };

次のコード例では、S3 バケット内のオブジェクトを一覧表示する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケット内のすべてのオブジェクトを一覧表示します。複数のオブジェクトがある場合、 IsTruncated と NextContinuationToken を使用してリスト全体を繰り返し処理します。

import { S3Client, // This command supersedes the ListObjectsCommand and is the recommended way to list objects. ListObjectsV2Command, } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new ListObjectsV2Command({ Bucket: "my-bucket", // The default and maximum number of keys returned is 1000. This limits it to // one for demonstration purposes. MaxKeys: 1, }); try { let isTruncated = true; console.log("Your bucket contains the following objects:\n"); let contents = ""; while (isTruncated) { const { Contents, IsTruncated, NextContinuationToken } = await client.send(command); const contentsList = Contents.map((c) => ` • ${c.Key}`).join("\n"); contents += contentsList + "\n"; isTruncated = IsTruncated; command.input.ContinuationToken = NextContinuationToken; } console.log(contents); } catch (err) { console.error(err); } };
  • API の詳細については、「 API リファレンス」の「 ListObjectsV2」を参照してください。 AWS SDK for JavaScript

次のコード例は、S3 バケットの新しいアクセスコントロールリスト (ACL) を設定する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

バケット ACL をプットします。

import { PutBucketAclCommand, GetBucketAclCommand, S3Client, } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Most Amazon S3 use cases don't require the use of access control lists (ACLs). // We recommend that you disable ACLs, except in unusual circumstances where // you need to control access for each object individually. // Consider a policy instead. For more information see https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-policies.html. export const main = async () => { // Grant a user READ access to a bucket. const command = new PutBucketAclCommand({ Bucket: "test-bucket", AccessControlPolicy: { Grants: [ { Grantee: { // The canonical ID of the user. This ID is an obfuscated form of your AWS account number. // It's unique to Amazon S3 and can't be found elsewhere. // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/finding-canonical-user-id.html. ID: "canonical-id-1", Type: "CanonicalUser", }, // One of FULL_CONTROL | READ | WRITE | READ_ACP | WRITE_ACP // https://docs.aws.amazon.com/AmazonS3/latest/API/API_Grant.html#AmazonS3-Type-Grant-Permission Permission: "FULL_CONTROL", }, ], Owner: { ID: "canonical-id-2", }, }, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例は、S3 バケットのウェブサイト設定を設定する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

ウェブサイト設定を設定します。

import { PutBucketWebsiteCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Set up a bucket as a static website. // The bucket needs to be publicly accessible. export const main = async () => { const command = new PutBucketWebsiteCommand({ Bucket: "test-bucket", WebsiteConfiguration: { ErrorDocument: { // The object key name to use when a 4XX class error occurs. Key: "error.html", }, IndexDocument: { // A suffix that is appended to a request that is for a directory. Suffix: "index.html", }, }, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

次のコード例では、S3 バケットにオブジェクトをアップロードする方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

オブジェクトをアップロードします。

import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new PutObjectCommand({ Bucket: "test-bucket", Key: "hello-s3.txt", Body: "Hello S3!", }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };

シナリオ

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

署名付き URL を作成して、オブジェクトをバケットにアップロードします。

import https from "https"; import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; import { fromIni } from "@aws-sdk/credential-providers"; import { HttpRequest } from "@smithy/protocol-http"; import { getSignedUrl, S3RequestPresigner, } from "@aws-sdk/s3-request-presigner"; import { parseUrl } from "@smithy/url-parser"; import { formatUrl } from "@aws-sdk/util-format-url"; import { Hash } from "@smithy/hash-node"; const createPresignedUrlWithoutClient = async ({ region, bucket, key }) => { const url = parseUrl(`https://${bucket}.s3.${region}.amazonaws.com/${key}`); const presigner = new S3RequestPresigner({ credentials: fromIni(), region, sha256: Hash.bind(null, "sha256"), }); const signedUrlObject = await presigner.presign( new HttpRequest({ ...url, method: "PUT" }), ); return formatUrl(signedUrlObject); }; const createPresignedUrlWithClient = ({ region, bucket, key }) => { const client = new S3Client({ region }); const command = new PutObjectCommand({ Bucket: bucket, Key: key }); return getSignedUrl(client, command, { expiresIn: 3600 }); }; function put(url, data) { return new Promise((resolve, reject) => { const req = https.request( url, { method: "PUT", headers: { "Content-Length": new Blob([data]).size } }, (res) => { let responseBody = ""; res.on("data", (chunk) => { responseBody += chunk; }); res.on("end", () => { resolve(responseBody); }); }, ); req.on("error", (err) => { reject(err); }); req.write(data); req.end(); }); } export const main = async () => { const REGION = "us-east-1"; const BUCKET = "example_bucket"; const KEY = "example_file.txt"; // There are two ways to generate a presigned URL. // 1. Use createPresignedUrl without the S3 client. // 2. Use getSignedUrl in conjunction with the S3 client and GetObjectCommand. try { const noClientUrl = await createPresignedUrlWithoutClient({ region: REGION, bucket: BUCKET, key: KEY, }); const clientUrl = await createPresignedUrlWithClient({ region: REGION, bucket: BUCKET, key: KEY, }); // After you get the presigned URL, you can provide your own file // data. Refer to put() above. console.log("Calling PUT using presigned URL without client"); await put(noClientUrl, "Hello World"); console.log("Calling PUT using presigned URL with client"); await put(clientUrl, "Hello World"); console.log("\nDone. Check your S3 console."); } catch (err) { console.error(err); } };

署名付き URL を作成して、オブジェクトをバケットからダウンロードします。

import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3"; import { fromIni } from "@aws-sdk/credential-providers"; import { HttpRequest } from "@smithy/protocol-http"; import { getSignedUrl, S3RequestPresigner, } from "@aws-sdk/s3-request-presigner"; import { parseUrl } from "@smithy/url-parser"; import { formatUrl } from "@aws-sdk/util-format-url"; import { Hash } from "@smithy/hash-node"; const createPresignedUrlWithoutClient = async ({ region, bucket, key }) => { const url = parseUrl(`https://${bucket}.s3.${region}.amazonaws.com/${key}`); const presigner = new S3RequestPresigner({ credentials: fromIni(), region, sha256: Hash.bind(null, "sha256"), }); const signedUrlObject = await presigner.presign(new HttpRequest(url)); return formatUrl(signedUrlObject); }; const createPresignedUrlWithClient = ({ region, bucket, key }) => { const client = new S3Client({ region }); const command = new GetObjectCommand({ Bucket: bucket, Key: key }); return getSignedUrl(client, command, { expiresIn: 3600 }); }; export const main = async () => { const REGION = "us-east-1"; const BUCKET = "example_bucket"; const KEY = "example_file.jpg"; try { const noClientUrl = await createPresignedUrlWithoutClient({ region: REGION, bucket: BUCKET, key: KEY, }); const clientUrl = await createPresignedUrlWithClient({ region: REGION, bucket: BUCKET, key: KEY, }); console.log("Presigned URL without client"); console.log(noClientUrl); console.log("\n"); console.log("Presigned URL with client"); console.log(clientUrl); } catch (err) { console.error(err); } };

次のコード例は、ウェブページに Amazon S3 オブジェクトを一覧表示する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

次のコードは、 AWS SDK を呼び出す関連する React コンポーネントです。このコンポーネントを含むアプリケーションの実行可能なバージョンは、前の GitHub リンクにあります。

import { useEffect, useState } from "react"; import { ListObjectsCommand, ListObjectsCommandOutput, S3Client, } from "@aws-sdk/client-s3"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; import "./App.css"; function App() { const [objects, setObjects] = useState< Required<ListObjectsCommandOutput>["Contents"] >([]); useEffect(() => { const client = new S3Client({ region: "us-east-1", // Unless you have a public bucket, you'll need access to a private bucket. // One way to do this is to create an Amazon Cognito identity pool, attach a role to the pool, // and grant the role access to the 's3:GetObject' action. // // You'll also need to configure the CORS settings on the bucket to allow traffic from // this example site. Here's an example configuration that allows all origins. Don't // do this in production. //[ // { // "AllowedHeaders": ["*"], // "AllowedMethods": ["GET"], // "AllowedOrigins": ["*"], // "ExposeHeaders": [], // }, //] // credentials: fromCognitoIdentityPool({ clientConfig: { region: "us-east-1" }, identityPoolId: "<YOUR_IDENTITY_POOL_ID>", }), }); const command = new ListObjectsCommand({ Bucket: "bucket-name" }); client.send(command).then(({ Contents }) => setObjects(Contents || [])); }, []); return ( <div className="App"> {objects.map((o) => ( <div key={o.ETag}>{o.Key}</div> ))} </div> ); } export default App;
  • API の詳細については、「 API リファレンスListObjects」の「」を参照してください。 AWS SDK for JavaScript

次のコードサンプルは、以下の操作方法を示しています。

  • バケットを作成し、そこにファイルをアップロードします。

  • バケットからオブジェクトをダウンロードします。

  • バケット内のサブフォルダにオブジェクトをコピーします。

  • バケット内のオブジェクトを一覧表示します。

  • バケットオブジェクトとバケットを削除します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

まず、必要なモジュールをすべてインポートします。

// Used to check if currently running file is this file. import { fileURLToPath } from "url"; import { readdirSync, readFileSync, writeFileSync } from "fs"; // Local helper utils. import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js"; import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js"; import { wrapText } from "@aws-doc-sdk-examples/lib/utils/util-string.js"; import { S3Client, CreateBucketCommand, PutObjectCommand, ListObjectsCommand, CopyObjectCommand, GetObjectCommand, DeleteObjectsCommand, DeleteBucketCommand, } from "@aws-sdk/client-s3";

前述のインポートでは、いくつかのヘルパーユーティリティを参照しています。これらのユーティリティは、このセクションの冒頭でリンクされた GitHub リポジトリにローカルです。参考までに、これらのユーティリティの以下の実装を参照してください。

export const dirnameFromMetaUrl = (metaUrl) => fileURLToPath(new URL(".", metaUrl)); import { select, input, confirm, checkbox } from "@inquirer/prompts"; export class Prompter { /** * @param {{ message: string, choices: { name: string, value: string }[]}} options */ select(options) { return select(options); } /** * @param {{ message: string }} options */ input(options) { return input(options); } /** * @param {string} prompt */ checkContinue = async (prompt = "") => { const prefix = prompt && prompt + " "; let ok = await this.confirm({ message: `${prefix}Continue?`, }); if (!ok) throw new Error("Exiting..."); }; /** * @param {{ message: string }} options */ confirm(options) { return confirm(options); } /** * @param {{ message: string, choices: { name: string, value: string }[]}} options */ checkbox(options) { return checkbox(options); } } export const wrapText = (text, char = "=") => { const rule = char.repeat(80); return `${rule}\n ${text}\n${rule}\n`; };

S3 のオブジェクトは「バケット」に保存されます。新しいバケットを作成する関数を定義しましょう。

export const createBucket = async () => { const bucketName = await prompter.input({ message: "Enter a bucket name. Bucket names must be globally unique:", }); const command = new CreateBucketCommand({ Bucket: bucketName }); await s3Client.send(command); console.log("Bucket created successfully.\n"); return bucketName; };

バケットには「オブジェクト」が含まれています。この関数は、ディレクトリの内容をバケットにオブジェクトとしてアップロードします。

export const uploadFilesToBucket = async ({ bucketName, folderPath }) => { console.log(`Uploading files from ${folderPath}\n`); const keys = readdirSync(folderPath); const files = keys.map((key) => { const filePath = `${folderPath}/${key}`; const fileContent = readFileSync(filePath); return { Key: key, Body: fileContent, }; }); for (let file of files) { await s3Client.send( new PutObjectCommand({ Bucket: bucketName, Body: file.Body, Key: file.Key, }), ); console.log(`${file.Key} uploaded successfully.`); } };

オブジェクトをアップロードしたら、正しくアップロードされたことを確認します。そのため ListObjects に を使用できます。ここでは 'Key' プロパティを使用しますが、レスポンスには他にも便利なプロパティがあります。

export const listFilesInBucket = async ({ bucketName }) => { const command = new ListObjectsCommand({ Bucket: bucketName }); const { Contents } = await s3Client.send(command); const contentsList = Contents.map((c) => ` • ${c.Key}`).join("\n"); console.log("\nHere's a list of files in the bucket:"); console.log(contentsList + "\n"); };

バケットから別のバケットにオブジェクトをコピーしたい場合があります。そのためには、 CopyObject コマンドを使用します。

export const copyFileFromBucket = async ({ destinationBucket }) => { const proceed = await prompter.confirm({ message: "Would you like to copy an object from another bucket?", }); if (!proceed) { return; } else { const copy = async () => { try { const sourceBucket = await prompter.input({ message: "Enter source bucket name:", }); const sourceKey = await prompter.input({ message: "Enter source key:", }); const destinationKey = await prompter.input({ message: "Enter destination key:", }); const command = new CopyObjectCommand({ Bucket: destinationBucket, CopySource: `${sourceBucket}/${sourceKey}`, Key: destinationKey, }); await s3Client.send(command); await copyFileFromBucket({ destinationBucket }); } catch (err) { console.error(`Copy error.`); console.error(err); const retryAnswer = await prompter.confirm({ message: "Try again?" }); if (retryAnswer) { await copy(); } } }; await copy(); } };

バケットから複数のオブジェクトを取得するための SDK メソッドはありません。代わりに、ダウンロードして繰り返し処理するオブジェクトのリストを作成します。

export const downloadFilesFromBucket = async ({ bucketName }) => { const { Contents } = await s3Client.send( new ListObjectsCommand({ Bucket: bucketName }), ); const path = await prompter.input({ message: "Enter destination path for files:", }); for (let content of Contents) { const obj = await s3Client.send( new GetObjectCommand({ Bucket: bucketName, Key: content.Key }), ); writeFileSync( `${path}/${content.Key}`, await obj.Body.transformToByteArray(), ); } console.log("Files downloaded successfully.\n"); };

では、リソースをクリーンアップしましょう。バケットを削除するには、そのバケットを空にしておく必要があります。これら 2 つの関数はバケットを空にして削除します。

export const emptyBucket = async ({ bucketName }) => { const listObjectsCommand = new ListObjectsCommand({ Bucket: bucketName }); const { Contents } = await s3Client.send(listObjectsCommand); const keys = Contents.map((c) => c.Key); const deleteObjectsCommand = new DeleteObjectsCommand({ Bucket: bucketName, Delete: { Objects: keys.map((key) => ({ Key: key })) }, }); await s3Client.send(deleteObjectsCommand); console.log(`${bucketName} emptied successfully.\n`); }; export const deleteBucket = async ({ bucketName }) => { const command = new DeleteBucketCommand({ Bucket: bucketName }); await s3Client.send(command); console.log(`${bucketName} deleted successfully.\n`); };

「main」関数はすべてをまとめます。このファイルを直接実行すると、main 関数が呼び出されます。

const main = async () => { const OBJECT_DIRECTORY = `${dirnameFromMetaUrl( import.meta.url, )}../../../../resources/sample_files/.sample_media`; try { console.log(wrapText("Welcome to the Amazon S3 getting started example.")); console.log("Let's create a bucket."); const bucketName = await createBucket(); await prompter.confirm({ message: continueMessage }); console.log(wrapText("File upload.")); console.log( "I have some default files ready to go. You can edit the source code to provide your own.", ); await uploadFilesToBucket({ bucketName, folderPath: OBJECT_DIRECTORY, }); await listFilesInBucket({ bucketName }); await prompter.confirm({ message: continueMessage }); console.log(wrapText("Copy files.")); await copyFileFromBucket({ destinationBucket: bucketName }); await listFilesInBucket({ bucketName }); await prompter.confirm({ message: continueMessage }); console.log(wrapText("Download files.")); await downloadFilesFromBucket({ bucketName }); console.log(wrapText("Clean up.")); await emptyBucket({ bucketName }); await deleteBucket({ bucketName }); } catch (err) { console.error(err); } };

次のコード例は、Amazon S3 との間で大きなファイルをアップロードまたはダウンロードする方法を示しています。

詳細については、「マルチパートアップロードを使用したオブジェクトのアップロード」を参照してください。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

サイズの大きいファイルをアップロードします。

import { CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand, AbortMultipartUploadCommand, S3Client, } from "@aws-sdk/client-s3"; const twentyFiveMB = 25 * 1024 * 1024; export const createString = (size = twentyFiveMB) => { return "x".repeat(size); }; export const main = async () => { const s3Client = new S3Client({}); const bucketName = "test-bucket"; const key = "multipart.txt"; const str = createString(); const buffer = Buffer.from(str, "utf8"); let uploadId; try { const multipartUpload = await s3Client.send( new CreateMultipartUploadCommand({ Bucket: bucketName, Key: key, }), ); uploadId = multipartUpload.UploadId; const uploadPromises = []; // Multipart uploads require a minimum size of 5 MB per part. const partSize = Math.ceil(buffer.length / 5); // Upload each part. for (let i = 0; i < 5; i++) { const start = i * partSize; const end = start + partSize; uploadPromises.push( s3Client .send( new UploadPartCommand({ Bucket: bucketName, Key: key, UploadId: uploadId, Body: buffer.subarray(start, end), PartNumber: i + 1, }), ) .then((d) => { console.log("Part", i + 1, "uploaded"); return d; }), ); } const uploadResults = await Promise.all(uploadPromises); return await s3Client.send( new CompleteMultipartUploadCommand({ Bucket: bucketName, Key: key, UploadId: uploadId, MultipartUpload: { Parts: uploadResults.map(({ ETag }, i) => ({ ETag, PartNumber: i + 1, })), }, }), ); // Verify the output by downloading the file from the Amazon Simple Storage Service (Amazon S3) console. // Because the output is a 25 MB string, text editors might struggle to open the file. } catch (err) { console.error(err); if (uploadId) { const abortCommand = new AbortMultipartUploadCommand({ Bucket: bucketName, Key: key, UploadId: uploadId, }); await s3Client.send(abortCommand); } } };

サイズの大きいファイルをダウンロードします。

import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3"; import { createWriteStream } from "fs"; const s3Client = new S3Client({}); const oneMB = 1024 * 1024; export const getObjectRange = ({ bucket, key, start, end }) => { const command = new GetObjectCommand({ Bucket: bucket, Key: key, Range: `bytes=${start}-${end}`, }); return s3Client.send(command); }; export const getRangeAndLength = (contentRange) => { const [range, length] = contentRange.split("/"); const [start, end] = range.split("-"); return { start: parseInt(start), end: parseInt(end), length: parseInt(length), }; }; export const isComplete = ({ end, length }) => end === length - 1; // When downloading a large file, you might want to break it down into // smaller pieces. Amazon S3 accepts a Range header to specify the start // and end of the byte range to be downloaded. const downloadInChunks = async ({ bucket, key }) => { const writeStream = createWriteStream( fileURLToPath(new URL(`./${key}`, import.meta.url)) ).on("error", (err) => console.error(err)); let rangeAndLength = { start: -1, end: -1, length: -1 }; while (!isComplete(rangeAndLength)) { const { end } = rangeAndLength; const nextRange = { start: end + 1, end: end + oneMB }; console.log(`Downloading bytes ${nextRange.start} to ${nextRange.end}`); const { ContentRange, Body } = await getObjectRange({ bucket, key, ...nextRange, }); writeStream.write(await Body.transformToByteArray()); rangeAndLength = getRangeAndLength(ContentRange); } }; export const main = async () => { await downloadInChunks({ bucket: "my-cool-bucket", key: "my-cool-object.txt", }); };