首页 > 解决方案 > 创建 Google 云存储桶会引发错误

问题描述

我的困境不是试图创建一个谷歌云存储桶,我可以这样做:

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({projectId: 'my-project', keyFilename: "key.json" });
async function createBucket() {
   await storage.createBucket('my-bucket');
};
createBucket().catch(console.error);

这很好用,但这不是我要调用我的函数来创建存储桶的方式。这是我在名为 cloudStorage.js 的文件中创建存储桶的函数:

 const { Storage } = require('@google-cloud/storage');

 const storage = new Storage({ projectId: 'my-project', keyFilename: "key.json" });
 module.exports = {
  createGoogleBucket: async ({ bucketName }) => {
      await storage.createBucket(bucketName);
  },
};

当我这样称呼它时:

  const  cloudStorage  = require('../src/cloudStorage');
  await cloudStorage.createGoogleBucket('my-bucket');

我收到以下错误:

   UnhandledPromiseRejectionWarning: TypeError: callback is not a function
  at C:\code\BigQueryDemo\node_modules\@google-cloud\storage\build\src\storage.js:312:17

为什么当我调用我的函数来创建存储桶时会引发此错误,我该如何解决?

谢谢

标签: node.jsecmascript-6google-cloud-storage

解决方案


您收到这条有些误导性的错误消息,因为谷歌云库认为您正在尝试传递回调而不是存储桶名称。发生这种情况是因为在此代码中:

  createGoogleBucket: async ({ bucketName }) => {
      await storage.createBucket(bucketName);
  },

({ bucketName })是一个解构赋值——它试图bucketName通过访问bucketName传递给函数的第一个参数的属性来分配一个局部变量。在这种情况下,您传递的是字符串文字 - 字符串文字没有bucketName属性。因此,您实际上是在传递undefinedstorage.createBucket(). 要修复,只需删除括号,这样您就不会尝试解构字符串:

  createGoogleBucket: async (bucketName) => {
      await storage.createBucket(bucketName);
  },

推荐阅读