【问题标题】:How to list all files uploaded to storage bucket in Google Storage Bucket?如何在谷歌存储桶中列出所有上传到存储桶的文件?
【发布时间】:2020-06-14 18:26:41
【问题描述】:

我在谷歌云存储桶中上传了许多文件。我想对该特定存储桶的所有文件的名称执行操作。 我怎样才能实现它?

【问题讨论】:

标签: node.js google-cloud-platform google-cloud-storage


【解决方案1】:

documentation 显示了使用提供的节点 SDK 列出存储桶中所有文件的示例。您将需要使用 Bucket 对象的 getFiles() 方法。

// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFiles() {
  // Lists files in the bucket
  const [files] = await storage.bucket(bucketName).getFiles();

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFiles().catch(console.error);

【讨论】:

    【解决方案2】:

    以下解决方案适用于客户端。 对于每个问题的 Node 环境,请参考 Doug Stevenson 的回答

    您需要使用listAll() 方法获取所有文件名。

    这是官方文档中的一个例子

    // Create a reference under which you want to list
    var listRef = storageRef.child('files/uid');
    
    // Find all the prefixes and items.
    listRef.listAll().then(function(res) {
      res.prefixes.forEach(function(folderRef) {
        // All the prefixes under listRef.
        // You may call listAll() recursively on them.
      });
      res.items.forEach(function(itemRef) {
        // All the items under listRef.
      });
    }).catch(function(error) {
      // Uh-oh, an error occurred!
    });
    

    我建议使用list 方法而不是listAll,因为后者将所有结果存储在内存中,而前者使用分页。

    Cloud Storage Documentation

    【讨论】:

    • 问题是关于nodejs。 Firebase SDK 在这里无济于事。
    猜你喜欢
    • 2020-04-10
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2015-03-01
    • 2013-05-07
    • 2015-10-08
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多