AWS S3 JavaScript SDK(v3)常用操作

安装 aws s3 sdk

shell 复制代码
npm install @aws-sdk/client-s3

配置

创建 ~/.aws/credentials 文件,添加以下配置项:

shell 复制代码
[default]
aws_access_key_id=<...>
aws_secret_access_key=<...>
region=<...>

S3 SDK常用桶操作

获取桶列表

typescript 复制代码
import {
    S3Client,
    Bucket,
    paginateListBuckets,
} from "@aws-sdk/client-s3";

async function listBuckets() {
    const client = new S3Client({});

    try {
        const buckets: Bucket[] = [];
        for await (const page of paginateListBuckets({ client }, {})) {
            if (page.Buckets) {
                buckets.push(...page.Buckets);
            }
        }
        console.log("Buckets: ", buckets);
    } catch (error) {
        console.error(error);
    }
}

创建桶

typescript 复制代码
import {
    S3Client,
    Bucket,
    CreateBucketCommand,
    waitUntilBucketExists,
} from "@aws-sdk/client-s3";

async function createBucket(bucket: string) {
    const client = new S3Client({});

    try {
        const { Location } = await client.send(
            new CreateBucketCommand({
                Bucket: bucket,
            })
        );
        await waitUntilBucketExists({ client, maxWaitTime: 1000 }, { Bucket: bucket });
        console.log(`Bucket created with location ${Location}`);
    } catch (error) {
        console.error(error);
    }
}

删除桶

typescript 复制代码
import {
    S3Client,
    Bucket,
    DeleteBucketCommand,
    waitUntilBucketExists,
} from "@aws-sdk/client-s3";

async function deleteBucket(bucket: string) {
    const client = new S3Client({});

    try {
        await client.send(
            new DeleteBucketCommand({
                Bucket: bucket,
            })
        );
        console.log("Bucket was deleted.");
    } catch (error) {
        console.error(error);
    }
}

S3 SDK常用对象操作

获取对象列表

typescript 复制代码
import {
    S3Client,
    Bucket,
    paginateListObjectsV2,
} from "@aws-sdk/client-s3";

async function listObjects(bucket: string) {
    const client = new S3Client({});

    try {
        const objects = [];
        const paginator = paginateListObjectsV2({ client, pageSize: 2 }, { Bucket: bucket });
        for await (const page of paginator) {
            if (page.Contents) {
                objects.push(page.Contents.map((o) => o.Key));
            }
        }
        console.log("Objects: ", objects);
    } catch (error) {
        console.error(error);
    }
}

获取对象

typescript 复制代码
import {
    S3Client,
    Bucket,
    GetObjectCommand,
} from "@aws-sdk/client-s3";

async function getObject(bucket: string, key: string) {
    const client = new S3Client({});

    try {
        const response = await client.send(
            new GetObjectCommand({
                Bucket: bucket,
                Key: key,
            })
        );
        if (response.Body) {
            console.log(await response.Body.transformToString());
        }
    } catch (error) {
        console.error(error);
    }
}

上传对象

typescript 复制代码
import {
    S3Client,
    Bucket,
    PutObjectCommand,
} from "@aws-sdk/client-s3";
import { readFile } from "node:fs/promises";

async function putObject(bucket: string, key: string, filePath: string) {
    const client = new S3Client({});

    try {
        const response = await client.send(
            new PutObjectCommand({
                Bucket: bucket,
                Key: key,
                Body: await readFile(filePath),
            })
        );
        console.log(response);
    } catch (error) {
        console.error(error);
    }
}

删除对象

typescript 复制代码
import {
    S3Client,
    Bucket,
    DeleteObjectCommand,
} from "@aws-sdk/client-s3";

async function deleteObject(bucket: string, key: string) {
    const client = new S3Client({});

    try {
        const response = await client.send(
            new DeleteObjectCommand({
                Bucket: bucket,
                Key: key,
            })
        );
        console.log(response);
    } catch (error) {
        console.error(error);
    }
}
相关推荐
创实信息2 天前
GitHub企业版:AWS CodeCommit迁移的最佳路径与技术优势
git·ci/cd·github·aws·github企业版·aws codecommit
九河云3 天前
《Amazon Bedrock vs ChatGPT:谁更胜一筹?》
人工智能·语言模型·chatgpt·云计算·aws
程序猿进阶4 天前
Spring boot启动原理及相关组件
java·网络·数据库·spring boot·后端·spring·aws
sealaugh324 天前
aws(学习笔记第十八课) 使用aws cdk(python)进行部署
笔记·学习·aws
AutoMQ4 天前
Kafka 迁移 AutoMQ 时 Flink 位点管理的挑战与解决方案
大数据·阿里云·云原生·kafka·云计算·腾讯云·aws·消息·gcp·计算·automq
AutoMQ5 天前
活动预告|云原生创新论坛:知乎携手 AutoMQ、OceanBase、快猫星云的实践分享
大数据·阿里云·云原生·kafka·云计算·腾讯云·aws·消息·gcp·计算·automq
范桂飓6 天前
AWS re:Invent 2024 — AI 基础设施架构
人工智能·架构·aws
九河云6 天前
Amazon Bedrock与AWS服务的无缝集成,如何打造智能化应用
人工智能·云计算·aws
weixin_307779138 天前
AWS云计算问答式知识库系统的实现
python·flask·云计算·fastapi·aws
胡八一9 天前
解决 AWS SDK for Java 连接 S3 文件系统Unable to load an HTTP implementation 问题
java·http·aws