aws-sdk-js-v3-usage

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Do 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

包结构

  • @aws-sdk/client-*
    — one per service, generated by smithy-typescript; one-to-one with AWS services and operations
  • @aws-sdk/lib-*
    — higher-level helpers (e.g.
    lib-dynamodb
    ,
    lib-storage
    )
  • @aws-sdk/*
    (no prefix) — utility packages (mostly internal; don't import deep paths)
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-sdk/client-*
    — 每个AWS服务对应一个包,由smithy-typescript生成;与AWS服务及操作一一对应
  • @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.
region
is always required; set it explicitly or via
AWS_REGION
env var.
js
const config = { region: "us-east-1", maxAttempts: 5 };
const s3 = new S3Client(config);
const dynamo = new DynamoDBClient(config);
Do not read or mutate
client.config
after instantiation
— it is a resolved form (e.g.
region
becomes an async function). See
references/effective-practices.md
.
For HTTP handler (
NodeHttpHandler
from
@smithy/node-http-handler
), retry strategy, endpoint details, logging, FIPS, dual-stack, protocol selection, and S3-specific options → see
references/clients.md
.
v3中没有全局配置——需为每个客户端传递配置。
region
始终是必填项;可显式设置或通过
AWS_REGION
环境变量设置。
js
const config = { region: "us-east-1", maxAttempts: 5 };
const s3 = new S3Client(config);
const dynamo = new DynamoDBClient(config);
请勿在实例化后读取或修改
client.config
——它是已解析的形式(例如
region
会变为异步函数)。详见
references/effective-practices.md
关于HTTP处理器(来自
@smithy/node-http-handler
NodeHttpHandler
)、重试策略、端点详情、日志、FIPS、双栈、协议选择及S3专属配置 → 请查看
references/clients.md

Credentials

凭证

All providers from
@aws-sdk/credential-providers
. Credentials are lazy and cached per client until ~5 min before expiry.
js
// 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
.
所有凭证提供者均来自
@aws-sdk/credential-providers
。凭证采用懒加载方式,并在客户端缓存至过期前约5分钟。
js
// 默认链(环境变量 → 配置文件 → 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.md

Streams (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
paginate*
functions instead of manual token handling:
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
@aws-sdk/lib-dynamodb
to work with native JS types instead of AttributeValues:
js
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
.
使用
@aws-sdk/lib-dynamodb
以原生JS类型而非AttributeValues进行操作:
js
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.md

S3: 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.md
.
js
// 预签名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.md

Error 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
e.name
or
instanceof
for specific error types. See
references/error-handling.md
for full patterns.
For runtime validation, serialization to non-default formats, or questions about what schemas are in jsv3 → see
references/schemas.md
.
js
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.name
instanceof
判断具体错误类型。完整模式请查看
references/error-handling.md
关于运行时验证、非默认格式序列化或jsv3中的schema相关问题 → 请查看
references/schemas.md

Performance: 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
await
the request and stream body separately — chain them. See
references/performance.md
.
js
// 配置maxSockets以匹配并行批处理大小
const client = new S3Client({
  requestHandler: { httpsAgent: { maxSockets: 50 } },
  cacheMiddleware: true, // 若使用自定义中间件则跳过
});
流死锁警告:在套接字数量有限的情况下,请勿分别
await
请求和流内容——请链式处理。详见
references/performance.md

Middleware

中间件

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):
initialize
serialize
build
finalizeRequest
deserialize
为客户端的所有命令添加自定义逻辑:
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 }
);
执行步骤(顺序):
initialize
serialize
build
finalizeRequest
deserialize

Abort 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
references/lambda.md
for Lambda layers and versioning.
在处理器外部初始化客户端(利用容器复用),在处理器内部发起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.md

Node.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
T | undefined
by default. Use
AssertiveClient
from
@smithy/types
to remove
| undefined
, or
NodeJsClient
/
BrowserClient
to narrow streaming blob types. See
references/typescript.md
.
响应字段默认类型为
T | undefined
。可使用
@smithy/types
中的
AssertiveClient
移除
| undefined
,或使用
NodeJsClient
/
BrowserClient
缩小流式blob类型范围。详见
references/typescript.md

SigV4a (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:
  • @aws-sdk/signature-v4-crt
    — Node.js only, better performance
  • @aws-sdk/signature-v4a
    — Node.js + browsers, pure JS
js
import "@aws-sdk/signature-v4a"; // side-effect only — no exported values needed
See
references/sigv4a.md
for full details and MRAP ARN format.
S3 MRAP及某些其他功能需要SigV4a。您必须安装并通过副作用导入以下其中一个包:
  • @aws-sdk/signature-v4-crt
    — 仅适用于Node.js,性能更优
  • @aws-sdk/signature-v4a
    — 适用于Node.js及浏览器,纯JS实现
js
import "@aws-sdk/signature-v4a"; // 仅副作用导入 — 无需导出值
完整详情及MRAP ARN格式请查看
references/sigv4a.md