【发布时间】:2020-06-14 18:26:41
【问题描述】:
我在谷歌云存储桶中上传了许多文件。我想对该特定存储桶的所有文件的名称执行操作。 我怎样才能实现它?
【问题讨论】:
-
我建议阅读云存储列表 API。 cloud.google.com/storage/docs/listing-objects
标签: node.js google-cloud-platform google-cloud-storage
我在谷歌云存储桶中上传了许多文件。我想对该特定存储桶的所有文件的名称执行操作。 我怎样才能实现它?
【问题讨论】:
标签: node.js google-cloud-platform google-cloud-storage
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);
【讨论】:
以下解决方案适用于客户端。 对于每个问题的 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,因为后者将所有结果存储在内存中,而前者使用分页。
【讨论】: