【问题标题】:How to get a list of files in a Google Cloud Storage folder using Node.js?如何使用 Node.js 获取 Google Cloud Storage 文件夹中的文件列表?
【发布时间】:2018-09-16 00:26:52
【问题描述】:

使用bucket.getFiles()可以获取一个bucket中的所有文件。

我的存储桶有数千个文件,我真的只想获取特定文件夹中文件的元数据。

documentation 不清楚如何从文件夹中获取文件。显然it is possible to limit the results 带有GetFilesRequest,但没有一个选项包括路径或文件夹,至少没有明确显示。

【问题讨论】:

    标签: node.js google-cloud-storage


    【解决方案1】:

    可以在选项中指定所需路径的前缀,例如

    async function readFiles () {
      const [files] = await bucket.getFiles({ prefix: 'users/user42'});
      console.log('Files:');
      files.forEach(file => {
        console.log(file.name);
      });
    };
    

    现在它终于可以在文档中找到了(感谢@Wajahath 的更新): https://googleapis.dev/nodejs/storage/latest/Bucket.html#getFiles

    【讨论】:

      【解决方案2】:

      Google 云存储没有文件夹/子目录。这是平面命名空间之上的一种错觉。即您所看到的子目录实际上是名称中带有“/”字符的对象。

      您可以在以下链接 https://cloud.google.com/storage/docs/gsutil/addlhelp/HowSubdirectoriesWork 上阅读有关 Google 云存储子目录如何工作的更多信息

      因此,通过将GetFilesRequestprefix 参数设置为您感兴趣的子目录名称,将返回您要查找的对象。

      【讨论】:

        【解决方案3】:

        如果您的存储桶中有大量文件,您可能需要考虑将它们列为流,以便在查询期间数据不会保留在内存中。

        GetFiles,一口气列出所有内容:

          admin.storage().bucket()
            .getFiles({ prefix: 'your-folder-name/', autoPaginate: false })
            .then((files) => {
              console.log(files);
            });
        

        getFilesStream,将所有内容都列为流:

          admin.storage().bucket()
            .getFilesStream({ prefix: 'your-folder-name/' })
            .on('error', console.error)
            .on('data', function (file) {
              console.log("received 'data' event");
              console.log(file.name);
            })
            .on('end', function () {
              console.log("received 'end' event");
            });
        

        完整文档和示例:link

        【讨论】:

          猜你喜欢
          • 2017-10-16
          • 1970-01-01
          • 2014-08-30
          • 1970-01-01
          • 2019-12-27
          • 1970-01-01
          • 1970-01-01
          • 2014-10-13
          • 2016-09-09
          相关资源
          最近更新 更多