安装 aws s3 sdk
npm install @aws-sdk/client-s3
配置
创建 ~/.aws/credentials 文件,添加以下配置项:
[default]
aws_access_key_id=<...>
aws_secret_access_key=<...>
region=<...>
S3 SDK常用桶操作
获取桶列表
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);
}
}
创建桶
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);
}
}
删除桶
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常用对象操作
获取对象列表
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);
}
}
获取对象
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);
}
}
上传对象
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);
}
}
删除对象
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);
}
}