获取目录文件列表

本SDK提供ListObjectsV2Command类用于获取目录文件列表。完整代码详见 GithubListObjectsV2Command调用的 S3 API 为 ListObjectsV2, 具体参见ListObjectsV2 API 文档

参数说明

  • Bucket: 文件所在的存储空间
  • MaxKeys: 请求返回的最大键数

示例

执行该示例前请确保配置文件的正确性
以下代码段需要在上下文中运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const s3 = require('./s3client');
const { ListObjectsV2Command } = require("@aws-sdk/client-s3");

async function listObjects(bucketName, maxKeys = 1000) {
    try {
        const command = new ListObjectsV2Command({
            Bucket: bucketName,
            MaxKeys: maxKeys
        });

        let isTruncated = true;
        let contents = "";
        let continuationToken;

        console.log("Your bucket contains the following objects:\n");

        while (isTruncated) {
            const params = { ...command.input };
            if (continuationToken) {
                params.ContinuationToken = continuationToken;
            }

            const response = await s3.send(new ListObjectsV2Command(params));
            const contentsList = response.Contents.map((c) => ` • ${c.Key}`).join("\n");
            contents += contentsList + "\n";
            isTruncated = response.IsTruncated;
            continuationToken = response.NextContinuationToken;
        }

        console.log(contents);
    } catch (err) {
        console.error("Error listing objects:", err);
    }
}

Example/ 目录中运行以下命令执行该示例

1
$ node ListObjects.js <bucketName> [maxKeys]