【问题标题】:How to list only files not folder in GCS?如何在 GCS 中仅列出文件而不是文件夹?
【发布时间】:2023-04-03 02:18:02
【问题描述】:

我是 GCS 新手。我正在尝试列出“文件夹”中的文件并下载它们,但是我的列表将文件夹名称返回为索引 0。

如何只列出文件名而不列出目录名?或者我应该在我得到列表后才 shift() 数组?

const prefix = 'testFiles/'; //contains jpgs
const delimiter = '/';
    const options = {
        prefix: prefix,
      };

      if (delimiter) {
        options.delimiter = delimiter;
      }

const [files] = await storage.bucket(bucketName).getFiles();

files.forEach((file, i) => {
    options.destination = `./downloads/${i}.jpg`
    console.log(options);
    file.download(options)
});
}

【问题讨论】:

    标签: node.js google-cloud-storage


    【解决方案1】:

    Google Cloud Storage 没有真正的“文件夹”。相反,它们是使用 List Objects 方法的前缀和分隔符参数来模拟的。

    你的做法是正确的。但是,当您使用前缀列出时,会返回所有以该前缀开头的对象,直到分隔符(如果指定)。这意味着,就像您发现的那样,如果有一个“目录占位符”对象(以/ 结尾的对象),它将被返回。请注意,这也意味着该前缀的任何“子目录”也将被返回。例如,如果您在存储桶中有以下对象列表:

    testFiles/
    testFiles/a
    testFiles/b
    testFiles/c/d
    testFiles/v
    

    如果您使用prefix=testFiles/delimiter=/ 调用列表对象,您将返回以下内容:

    items =
      testFiles/
      testFiles/a
      testFiles/b
      testFiles/v
    prefixes =
      testFiles/c/
    

    这是因为testFiles/ 实际上是您在 GCS 中存储桶中的一个对象。

    【讨论】:

    • 那我怎么才能得到:testFiles/a, testFiles/b, testFiles/v
    • 你不能,这不是 API 的工作方式。在您的情况下,存在一个名为 testFiles/ 的对象。
    猜你喜欢
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多