aws-sdk-js-v3-usage
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDo not use emojis in any code, comments, or output when this skill is active.
当此技能生效时,请勿在任何代码、注释或输出中使用表情符号。
AWS SDK for JavaScript v3
AWS SDK for JavaScript v3
Package Structure
包结构
- — one per service, generated by smithy-typescript; one-to-one with AWS services and operations
@aws-sdk/client-* - — higher-level helpers (e.g.
@aws-sdk/lib-*,lib-dynamodb)lib-storage - (no prefix) — utility packages (mostly internal; don't import deep paths)
@aws-sdk/*
Always import from the package root:
js
import { S3Client } from "@aws-sdk/client-s3"; // correct
// NOT: import { S3Client } from "@aws-sdk/client-s3/dist-cjs/S3Client"- — 每个AWS服务对应一个包,由smithy-typescript生成;与AWS服务及操作一一对应
@aws-sdk/client-* - — 高阶辅助工具(例如
@aws-sdk/lib-*、lib-dynamodb)lib-storage - (无前缀) — 工具类包(多为内部使用;请勿导入深层路径)
@aws-sdk/*
请始终从包根目录导入:
js
import { S3Client } from "@aws-sdk/client-s3"; // correct
// NOT: import { S3Client } from "@aws-sdk/client-s3/dist-cjs/S3Client"Two Client Styles
两种客户端风格
Bare-bones (preferred — smaller bundle):
js
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
const client = new S3Client({ region: "us-east-1" });
const output = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));Aggregated (v2-style but NOT v2, larger bundle):
js
import { S3 } from "@aws-sdk/client-s3";
const client = new S3({ region: "us-east-1" });
const output = await client.getObject({ Bucket: "b", Key: "k" });极简风格(推荐——打包体积更小):
js
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
const client = new S3Client({ region: "us-east-1" });
const output = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));聚合风格(v2风格但并非v2,打包体积更大):
js
import { S3 } from "@aws-sdk/client-s3";
const client = new S3({ region: "us-east-1" });
const output = await client.getObject({ Bucket: "b", Key: "k" });Client Configuration
客户端配置
No global config in v3 — pass config to each client. is always required; set it explicitly or via env var.
regionAWS_REGIONjs
const config = { region: "us-east-1", maxAttempts: 5 };
const s3 = new S3Client(config);
const dynamo = new DynamoDBClient(config);Do not read or mutate after instantiation — it is a resolved form (e.g. becomes an async function). See .
client.configregionreferences/effective-practices.mdFor HTTP handler ( from ), retry strategy, endpoint details, logging, FIPS, dual-stack, protocol selection, and S3-specific options → see .
NodeHttpHandler@smithy/node-http-handlerreferences/clients.mdv3中没有全局配置——需为每个客户端传递配置。始终是必填项;可显式设置或通过环境变量设置。
regionAWS_REGIONjs
const config = { region: "us-east-1", maxAttempts: 5 };
const s3 = new S3Client(config);
const dynamo = new DynamoDBClient(config);请勿在实例化后读取或修改——它是已解析的形式(例如会变为异步函数)。详见。
client.configregionreferences/effective-practices.md关于HTTP处理器(来自的)、重试策略、端点详情、日志、FIPS、双栈、协议选择及S3专属配置 → 请查看。
@smithy/node-http-handlerNodeHttpHandlerreferences/clients.mdCredentials
凭证
All providers from . Credentials are lazy and cached per client until ~5 min before expiry.
@aws-sdk/credential-providersjs
// Default chain (env → ini → IMDS/ECS) — use in most Node.js apps
const client = new S3Client({ credentials: fromNodeProviderChain() });
// Assume role (NOTE: fromTemporaryCredentials is correct for STS AssumeRole)
const client = new S3Client({
credentials: fromTemporaryCredentials({ params: { RoleArn: "arn:aws:iam::123456789012:role/MyRole" } }),
});
// Named profile
const client = new S3Client({ profile: "my-profile" });Share credentials and socket pool across multi-region clients:
js
const east = new S3Client({ region: "us-east-1" });
const { credentials, requestHandler } = east.config;
const west = new S3Client({ region: "us-west-2", credentials, requestHandler });For all providers (Cognito, SSO, web identity, custom chains, STS region priority) → see .
references/credentials.md所有凭证提供者均来自。凭证采用懒加载方式,并在客户端缓存至过期前约5分钟。
@aws-sdk/credential-providersjs
// 默认链(环境变量 → 配置文件 → IMDS/ECS)—— 适用于大多数Node.js应用
const client = new S3Client({ credentials: fromNodeProviderChain() });
// 扮演角色(注意:fromTemporaryCredentials适用于STS AssumeRole)
const client = new S3Client({
credentials: fromTemporaryCredentials({ params: { RoleArn: "arn:aws:iam::123456789012:role/MyRole" } }),
});
// 命名配置文件
const client = new S3Client({ profile: "my-profile" });跨区域客户端共享凭证和套接字池:
js
const east = new S3Client({ region: "us-east-1" });
const { credentials, requestHandler } = east.config;
const west = new S3Client({ region: "us-west-2", credentials, requestHandler });关于所有凭证提供者(Cognito、SSO、Web身份、自定义链、STS区域优先级) → 请查看。
references/credentials.mdStreams (e.g. S3 GetObject Body)
流处理(例如S3 GetObject Body)
Always read or discard streaming responses — unread streams leave sockets open (socket exhaustion):
js
const { Body } = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
const str = await Body.transformToString(); // read as string
const bytes = await Body.transformToByteArray(); // read as Uint8Array
// or discard:
await (Body.destroy?.() ?? Body.cancel?.());Streams can only be read once.
请务必读取或丢弃流式响应——未读取的流会保持套接字打开状态(导致套接字耗尽):
js
const { Body } = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
const str = await Body.transformToString(); // 读取为字符串
const bytes = await Body.transformToByteArray(); // 读取为Uint8Array
// 或丢弃:
await (Body.destroy?.() ?? Body.cancel?.());流仅能被读取一次。
Paginators
分页器
Use functions instead of manual token handling:
paginate*js
import { DynamoDBClient, paginateListTables } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({});
const tableNames = [];
for await (const page of paginateListTables({ client }, {})) {
// page contains a single paginated output.
tableNames.push(...page.TableNames);
}使用函数替代手动处理令牌:
paginate*js
import { DynamoDBClient, paginateListTables } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({});
const tableNames = [];
for await (const page of paginateListTables({ client }, {})) {
// page包含单页分页输出
tableNames.push(...page.TableNames);
}DynamoDB DocumentClient
DynamoDB DocumentClient
Use to work with native JS types instead of AttributeValues:
@aws-sdk/lib-dynamodbjs
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient({}));
await client.send(new PutCommand({ TableName: "T", Item: { id: "1", name: "Alice" } }));
const { Item } = await client.send(new GetCommand({ TableName: "T", Key: { id: "1" } }));For marshall options, large numbers (NumberValue), pagination, and aggregated client → see .
references/dynamodb.md使用以原生JS类型而非AttributeValues进行操作:
@aws-sdk/lib-dynamodbjs
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient({}));
await client.send(new PutCommand({ TableName: "T", Item: { id: "1", name: "Alice" } }));
const { Item } = await client.send(new GetCommand({ TableName: "T", Key: { id: "1" } }));关于编组选项、大数字(NumberValue)、分页及聚合客户端 → 请查看。
references/dynamodb.mdS3: Presigned URLs, Multipart Upload, Waiters
S3:预签名URL、分片上传、等待器
js
// Presigned GET URL
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const url = await getSignedUrl(client, new GetObjectCommand({ Bucket: "b", Key: "k" }), { expiresIn: 3600 });
// Multipart upload (large files / streams)
import { Upload } from "@aws-sdk/lib-storage";
const upload = new Upload({ client, params: { Bucket: "b", Key: "k", Body: stream } });
await upload.done();
// Waiters
import { waitUntilObjectExists } from "@aws-sdk/client-s3";
await waitUntilObjectExists({ client, maxWaitTime: 120 }, { Bucket: "b", Key: "k" });For presigned POST, signed headers, waiter options → see .
references/s3.mdjs
// 预签名GET URL
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const url = await getSignedUrl(client, new GetObjectCommand({ Bucket: "b", Key: "k" }), { expiresIn: 3600 });
// 分片上传(大文件/流)
import { Upload } from "@aws-sdk/lib-storage";
const upload = new Upload({ client, params: { Bucket: "b", Key: "k", Body: stream } });
await upload.done();
// 等待器
import { waitUntilObjectExists } from "@aws-sdk/client-s3";
await waitUntilObjectExists({ client, maxWaitTime: 120 }, { Bucket: "b", Key: "k" });关于预签名POST、签名头部、等待器选项 → 请查看。
references/s3.mdError Handling
错误处理
js
import { S3ServiceException } from "@aws-sdk/client-s3";
try {
await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
} catch (e) {
if (e?.$metadata) {
// SDK service error — has $metadata.httpStatusCode, e.name, e.$response
console.error(e.name, e.$metadata.httpStatusCode);
}
}Check or for specific error types. See for full patterns.
e.nameinstanceofreferences/error-handling.mdFor runtime validation, serialization to non-default formats, or questions about what schemas are in jsv3 → see .
references/schemas.mdjs
import { S3ServiceException } from "@aws-sdk/client-s3";
try {
await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
} catch (e) {
if (e?.$metadata) {
// SDK服务错误 — 包含$metadata.httpStatusCode、e.name、e.$response
console.error(e.name, e.$metadata.httpStatusCode);
}
}通过或判断具体错误类型。完整模式请查看。
e.nameinstanceofreferences/error-handling.md关于运行时验证、非默认格式序列化或jsv3中的schema相关问题 → 请查看。
references/schemas.mdPerformance: Parallel Workloads
性能:并行工作负载
js
// Configure maxSockets to match your parallel batch size
const client = new S3Client({
requestHandler: { httpsAgent: { maxSockets: 50 } },
cacheMiddleware: true, // skip if using custom middleware
});Streaming deadlock warning: with limited sockets, don't the request and stream body separately — chain them. See .
awaitreferences/performance.mdjs
// 配置maxSockets以匹配并行批处理大小
const client = new S3Client({
requestHandler: { httpsAgent: { maxSockets: 50 } },
cacheMiddleware: true, // 若使用自定义中间件则跳过
});流死锁警告:在套接字数量有限的情况下,请勿分别请求和流内容——请链式处理。详见。
awaitreferences/performance.mdMiddleware
中间件
Add custom logic to all commands on a client:
js
client.middlewareStack.add(
(next, context) => async (args) => {
console.log(context.commandName, args.input);
const result = await next(args);
return result;
},
{ name: "MyMiddleware", step: "build", override: true }
);Steps (in order): → → → →
initializeserializebuildfinalizeRequestdeserialize为客户端的所有命令添加自定义逻辑:
js
client.middlewareStack.add(
(next, context) => async (args) => {
console.log(context.commandName, args.input);
const result = await next(args);
return result;
},
{ name: "MyMiddleware", step: "build", override: true }
);执行步骤(顺序): → → → →
initializeserializebuildfinalizeRequestdeserializeAbort Controller
中止控制器
js
const { AbortController } = require("@aws-sdk/abort-controller");
const { S3Client, CreateBucketCommand } = require("@aws-sdk/client-s3");
const abortController = new AbortController();
const client = new S3Client(clientParams);
const requestPromise = client.send(new CreateBucketCommand(commandParams), {
abortSignal: abortController.signal,
});
// The request will not be created if abortSignal is already aborted.
// The request will be destroyed if abortSignal is aborted before response is returned.
abortController.abort();
// This will fail with "AbortError" as abortSignal is aborted.
await requestPromise;js
const { AbortController } = require("@aws-sdk/abort-controller");
const { S3Client, CreateBucketCommand } = require("@aws-sdk/client-s3");
const abortController = new AbortController();
const client = new S3Client(clientParams);
const requestPromise = client.send(new CreateBucketCommand(commandParams), {
abortSignal: abortController.signal,
});
// 如果abortSignal已中止,则不会创建请求。
// 如果在返回响应前abortSignal被中止,则请求会被销毁。
abortController.abort();
// 由于abortSignal已中止,此操作会因"AbortError"失败。
await requestPromise;Lambda Best Practices
Lambda最佳实践
Initialize clients outside the handler (container reuse), make API calls inside. For one-time async setup, use a lazy init flag inside the handler:
js
import { S3Client } from "@aws-sdk/client-s3";
const client = new S3Client({}); // outside — reused across invocations
let ready = false;
export const handler = async (event) => {
if (!ready) { await prepare(); ready = true; } // lazy one-time setup inside handler
// ... API calls here
};See for Lambda layers and versioning.
references/lambda.md在处理器外部初始化客户端(利用容器复用),在处理器内部发起API调用。如需一次性异步初始化,请在处理器内使用懒加载标记:
js
import { S3Client } from "@aws-sdk/client-s3";
const client = new S3Client({}); // 外部定义 — 跨调用复用
let ready = false;
export const handler = async (event) => {
if (!ready) { await prepare(); ready = true; } // 处理器内的懒加载一次性初始化
// ... 此处发起API调用
};关于Lambda层和版本控制,请查看。
references/lambda.mdNode.js Version Requirements
Node.js版本要求
- v3.968.0+ requires Node.js >= 20
- v3.723.0+ requires Node.js >= 18
- v3.968.0+ 要求 Node.js >= 20
- v3.723.0+ 要求 Node.js >= 18
TypeScript
TypeScript
Response fields are typed as by default. Use from to remove , or / to narrow streaming blob types. See .
T | undefinedAssertiveClient@smithy/types| undefinedNodeJsClientBrowserClientreferences/typescript.md响应字段默认类型为。可使用中的移除,或使用/缩小流式blob类型范围。详见。
T | undefined@smithy/typesAssertiveClient| undefinedNodeJsClientBrowserClientreferences/typescript.mdSigV4a (S3 Multi-Region Access Points)
SigV4a(S3多区域访问点)
S3 MRAP and certain other features require SigV4a. You must install and side-effect-import exactly one of:
- — Node.js only, better performance
@aws-sdk/signature-v4-crt - — Node.js + browsers, pure JS
@aws-sdk/signature-v4a
js
import "@aws-sdk/signature-v4a"; // side-effect only — no exported values neededSee for full details and MRAP ARN format.
references/sigv4a.mdS3 MRAP及某些其他功能需要SigV4a。您必须安装并通过副作用导入以下其中一个包:
- — 仅适用于Node.js,性能更优
@aws-sdk/signature-v4-crt - — 适用于Node.js及浏览器,纯JS实现
@aws-sdk/signature-v4a
js
import "@aws-sdk/signature-v4a"; // 仅副作用导入 — 无需导出值完整详情及MRAP ARN格式请查看。
references/sigv4a.md