Node.js上传至Google Cloud Storage报错:'bucketName'已声明
修复Google Cloud Storage上传代码中的重复声明错误
你遇到的'bucketName' has already been declared错误很明确——函数参数已经定义了bucketName和filename,但你在函数内部又用var重新声明了这两个同名变量,JavaScript不允许同一作用域内重复声明变量,尤其是参数+var的组合会直接触发这个报错。
下面是修复后的完整代码,同时我还优化了一些细节让代码更灵活健壮:
修复后的代码
async function uploadFile(bucketName = 'mybucket-saturday', filename = 'demo.txt') { // [START storage_upload_file] // Imports the Google Cloud client library const { Storage } = require('@google-cloud/storage'); // Your Google Cloud Platform project ID const projectId = 'apple-ration-27434'; // Creates a client with explicit project association const storage = new Storage({ projectId }); // Uploads a local file to the bucket await storage.bucket(bucketName).upload(filename, { // Support for HTTP requests made with `Accept-Encoding: gzip` gzip: true, metadata: { // Enable long-lived HTTP caching headers // Use only if the contents of the file will never change // (If the contents will change, use cacheControl: 'no-cache') cacheControl: 'public, max-age=31536000', }, }); console.log(`${filename} uploaded to ${bucketName}.`); // [END storage_upload_file] }
核心修复与优化点
- 移除了函数内部重复声明的
var bucketName和var filename,改为给函数参数设置默认值。这样既保留了你原本想用的默认存储桶和文件名,又允许你在调用时传入自定义值(比如uploadFile('my-custom-bucket', 'my-test-file.txt')),灵活性更高。 - 将
projectId传入Storage构造函数,确保Google Cloud客户端明确关联到你的项目,避免潜在的权限或项目不匹配问题。 - 保留了你原本的上传配置(gzip压缩、缓存控制),逻辑完全不变。
额外注意事项
- 确认Lambda中
GOOGLE_APPLICATION_CREDENTIALS指向的服务账号密钥,拥有目标存储桶的写入权限(比如storage.objects.create权限)。 - 本地测试时,确保已经通过
gcloud auth application-default login或者设置环境变量完成了Google Cloud的认证配置。
内容的提问来源于stack exchange,提问作者Gracie
相关产品推荐
相关产品推荐

