You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cloud Function的Bucket API获取GCP GCS顶级文件夹?

问题

我有一个GCS存储桶,里面包含以下对象:

myfile.pdf
myimg.png
folder001/stuff/<some files or deep folders>
folder002/<some files or deep folders>
.
.
.
someOtherFolderName00n/<some files or deep folders>

我希望只获取顶级文件夹列表,比如 folder001, ..., someOtherFolderName00n。

我在GCP Cloud Functions中使用Bucket API写了这段代码:

const admin = require('firebase-admin');
admin.initializeApp();
const sourceBucket = admin.storage().bucket("test_source_001");
exports.my_function = async (event, context) => {
    // get top level bucket folders
    const [sourceFiles] = await sourceBucket.getFiles({
        prefix: '',
        delimiter: '/'
    });

    // extract name property from each object
    const sourceFileNames = sourceFiles.map((file) => file.name);

    console.log(sourceFileNames)
};

但这段代码返回了存储桶里的所有内容(包括无后缀/的顶级文件),却没返回顶级文件夹,得到的列表如下:

myfile.pdf
myimg.png
folder001/stuff/
folder001/stuff/file1
...
folder001/stuff/fileN
folder002/file1
...
folder002/fileN
...
someOtherFolderName00n/file1
...
someOtherFolderName00n/fileN

我可以通过下面的方式处理得到结果:

s = new Set()
for (let f of sourceFileNames) {
    s.add(f.split('/')[0])
}

但我想知道能不能直接通过getFiles查询返回顶级文件夹?(我刚接触GCP和Cloud Functions,可能漏了简单的配置)

解决方案

你之前的代码只获取了getFiles返回的第一个结果(文件数组),忽略了第二个包含前缀集合的响应对象——这正是你要的顶级文件夹。

修改后的代码如下:

const admin = require('firebase-admin');
admin.initializeApp();
const sourceBucket = admin.storage().bucket("test_source_001");
exports.my_function = async (event, context) => {
    // 同时获取文件列表和前缀(文件夹)信息
    const [sourceFiles, response] = await sourceBucket.getFiles({
        prefix: '',
        delimiter: '/'
    });

    // response.prefixes 包含所有带末尾斜杠的顶级文件夹路径,如 ['folder001/', 'folder002/']
    const topLevelFolders = response.prefixes.map(prefix => prefix.slice(0, -1));
    console.log(topLevelFolders); // 输出 ['folder001', 'folder002', ...]
};

关键说明:

  • 当配置delimiter: '/'时,GCS API会自动将所有匹配前缀、被分隔符截断的路径归类到response.prefixes中,这些就是逻辑上的"文件夹"
  • 如果你不需要顶级文件(如myfile.pdf),可以完全忽略sourceFiles,直接使用response.prefixes
  • 用slice(0, -1)去掉路径末尾的斜杠,就能得到纯文件夹名称

内容的提问来源于stack exchange,提问作者lampShadesDrifter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 04:01:25