【发布时间】:2020-04-08 19:18:23
【问题描述】:
我正在做一个项目,我需要访问 gcloud 存储桶中的一些对象
它适用于 GOOGLE_APPLICATION_CREDENTIALS 环境变量,但当我尝试使用 Storage 构造函数的 keyfilename 选项时却不行。这是一个显示正在发生的事情的最小示例:
const {Storage, File} = require('@google-cloud/storage');
const path = require("path");
// Fake bucket and file names
const bucketname = "my-bucket";
const filename = "test-file.txt";
// Points to a valid key file for a service account with read & write access to the bucket
const keyPath = path.resolve("./key.json");
const storage = new Storage({keyFile: keyPath}); // note that I'm providing a keyFile here
const bucket = storage.bucket(bucketname);
const file = new File(bucket, filename);
async function main() {
console.log("try without GOOGLE_APPLICATION_CREDENTIALS");
try {
await file.download({ destination: "./test.txt" });
console.log("ok");
return;
} catch (e) {
console.log(e.message);
}
console.log("try with GOOGLE_APPLICATION_CREDENTIALS");
try {
process.env["GOOGLE_APPLICATION_CREDENTIALS"] = keyPath;
await file.download({ destination: "./test.txt" });
console.log("ok");
return;
} catch (e) {
console.log("failed with GOOGLE_APPLICATION_CREDENTIALS");
console.log(e.message);
}
}
main();
我希望这个输出是:
try without GOOGLE_APPLICATION_CREDENTIALS
ok
但我得到了
try without GOOGLE_APPLICATION_CREDENTIALS
Anonymous caller does not have storage.objects.get access to my-bucket/test-file.txt.
try with GOOGLE_APPLICATION_CREDENTIALS
ok
这是怎么回事?
【问题讨论】:
标签: node.js google-cloud-platform google-cloud-storage