AWS SDK for JavaScriptを使って、S3のファイルをあれこれする方法を調べたので、その時の備忘録
以下のGitHubリポジトリに全部まとまってるので、
S3以外が必要なときはここを見るといい感じ。
・aws-sdk-js-v3/clients/client-s3
使い方
まずはインストール
$ npm install @aws-sdk/client-s3
使い方はこんな感じ。
import { S3Client, PutObjectCommand, PutObjectCommandInput, ListObjectsCommand, ListObjectsCommandInput, DeleteObjectsCommand, DeleteObjectsCommandInput } from "@aws-sdk/client-s3"; const BUCKET_NAME = "your_bucket_name" // クライアントの初期化 const s3Client = new S3Client({ region: AWS_REGION, credentials: { accessKeyId: "your_aws_access_key_id", secretAccessKey: "your_aws_secret_access_key_id" } }); // アップロード: PutObjectCommand const uploadParams: PutObjectCommandInput = { Bucket: BUCKET_NAME, Key: "your/upload/location/file.txt", Body: "File Contents" }; const uploadRes = await s3Client.send(new PutObjectCommand(uploadParams)); console.log("Success", uploadRes); // 一覧の取得: ListObjectsCommand const listParams: ListObjectsCommandInput = { Bucket: BUCKET_NAME, Prefix: "your/upload/location", }; const listRes = await s3Client.send(new ListObjectsCommand(listParams)); console.log("Success", listRes); // listRes.Contentsにファイルの情報が含まれる // 削除: DeleteObjectsCommand const deleteParams: DeleteObjectsCommandInput = { Bucket: BUCKET_NAME, Delete: { Objects: [{ Key:"your/upload/location/file.txt" }] }, }; const deleteRes = await s3Client.send(new DeleteObjectsCommand(deleteParams)); console.log("Success", deleteRes);
以上!!