如何使用 Node.js获取 Google Cloud Storage 文件夹中的文件列表



使用bucket.getFiles()可以获取存储桶中的所有文件。

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

文档不清楚如何仅从文件夹中获取文件。显然,可以使用GetFilesRequest限制结果,但没有一个选项包括路径或文件夹,至少没有明确包含。

可以在

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

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

Google Cloud Storage 没有文件夹/子目录。这是平面命名空间顶部的幻觉。即您看到的子目录实际上是名称中包含"/"字符的对象。

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

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

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

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");
    });

完整文档和示例:链接

最新更新