【问题标题】:List only top level folders in GCP GCS from Cloud Function bucket API?仅列出来自 Cloud Function bucket API 的 GCP GCS 中的顶级文件夹?
【发布时间】:2022-12-03 11:30:26
【问题描述】:

从 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 的代码 sn-p 看起来像......

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,所以想知道我是否只是在这里遗漏了一些简单的东西)。

【问题讨论】:

  • 文件夹位于apiResponse.prefixes。您将需要扩展您的代码:bucket.getFiles({autoPaginate: false, delimiter: '/'}, function(err, files, nextQuery, apiResponse) {}

标签: google-cloud-functions google-cloud-storage


【解决方案1】:

可以在选项中指定所需路径的前缀。

前缀和分隔符可用于模拟目录列表。 前缀可用于过滤以前缀开头的对象。 定界符参数可用于将结果限制为仅给定“目录”中的对象。如果没有定界符,则返回前缀下的整棵树。

如果您只想列出文件夹,请尝试像这样更改前缀:

const [sourceFiles] = await sourceBucket.getFiles({
        prefix: 'folder',
        delimiter: '/'
    });

有关更多信息,请参阅 how to specify prefixes 上的此文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2023-04-03
    • 2023-01-20
    相关资源
    最近更新 更多