如何使用AWS S3 Node.js SDK V3的GetObjectCommand通过通配符获取对象?
使用AWS S3 Node.js SDK V3获取前缀为123_的对象
首先明确:GetObjectCommand本身只能获取单个S3对象,不支持直接用通配符批量获取。要拿到所有以123_开头的对象,得先通过列表命令筛选出符合条件的对象,再逐个调用GetObjectCommand获取内容。
实现步骤及代码示例
- 先使用
ListObjectsV2Command列出所有前缀为123_的对象(S3的前缀匹配是精确前缀匹配,不需要通配符,直接指定123_即可) - 遍历返回的对象列表,对每个对象的
Key调用GetObjectCommand获取内容
以下是完整的代码示例:
import { S3Client, ListObjectsV2Command, GetObjectCommand } from "@aws-sdk/client-s3"; // 初始化S3客户端 const s3Client = new S3Client({ region: "你的区域" }); const bucketName = "你的存储桶名称"; const targetPrefix = "123_"; async function getObjectsByPrefix() { // 第一步:列出符合前缀条件的对象 const listCommand = new ListObjectsV2Command({ Bucket: bucketName, Prefix: targetPrefix }); const listResponse = await s3Client.send(listCommand); // 如果没有匹配的对象,直接返回 if (!listResponse.Contents) return; // 第二步:逐个获取对象内容 const objectContents = []; for (const obj of listResponse.Contents) { const getCommand = new GetObjectCommand({ Bucket: bucketName, Key: obj.Key }); const getResponse = await s3Client.send(getCommand); // 将对象内容转换为字符串(根据实际需求处理,比如Buffer、JSON等) const content = await getResponse.Body.transformToString(); objectContents.push({ key: obj.Key, content }); } return objectContents; } // 调用函数并处理结果 getObjectsByPrefix() .then(result => console.log("获取到的对象内容:", result)) .catch(err => console.error("出错了:", err));
关键说明
- S3的前缀匹配逻辑是匹配对象Key以指定字符串开头的所有对象,这里用
Prefix: '123_'就能精准筛选出你需要的对象,无需使用通配符。 - 如果存储桶中符合条件的对象数量较多(超过1000个),需要处理分页逻辑,
ListObjectsV2Command会返回NextContinuationToken,可以循环调用直到没有更多对象。
内容的提问来源于stack exchange,提问作者IgorAlves
相关产品推荐
相关产品推荐

