【问题标题】:How to get list of public urls for google cloud storage with NodeJs client instead of storage object如何使用 NodeJs 客户端而不是存储对象获取谷歌云存储的公共 URL 列表
【发布时间】:2021-07-19 14:25:39
【问题描述】:
运行(new Storage()).bucket('my-bucket-name').getFiles() 时,我得到一个带有this structure 的对象列表。所有项目都设置为公共,我宁愿不处理对象以“手工”(https://storage.cloud.google.com/[object.metadata.bucket]/[object.metadata.name])拼凑公共网址,我想知道 GCP 的 NodeJs 客户端是否提供类似的东西。
我发现了一个类似的链接here 除了python。
谢谢!
【问题讨论】:
标签:
google-cloud-platform
google-cloud-storage
google-api-nodejs-client
【解决方案1】:
正如您发布的主题中所述,没有直接的方法可以通过 Google 现有的客户端库来执行此操作。有一些对象可以让您直接获取 URL,但并非所有对象都可以。
因此,在代码中拼凑 URL 会更安全。正如您所提到的,以及通过 this document 在 Google 文档中提到的,您可以使用 URL 模式 http(s)://storage.googleapis.com/[bucket]/[object] 来快速构建 URL。
给定API的响应,你可以通过一个小循环比如
function main(bucketName = 'my-bucket') {
// The ID of your GCS bucket
const bucketName = 'your-unique-bucket-name';
// The string for the URL
const url = 'https://storage.googleapis.com/';
// 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('URLs:');
files.forEach(file => {
console.log(url.concat(bucketName,'/',file.name));
});
}
listFiles().catch(console.error);
}
这是改编自GCPs GitHub上列出文件的示例代码