创建Google云存储桶会引发错误

时间:2020-02-25 15:45:50

标签: node.js ecmascript-6 google-cloud-storage

我的困境不是尝试创建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

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

谢谢

1 个答案:

答案 0 :(得分:2)

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

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

({ bucketName })destructuring assignment-它尝试通过访问传递给函数的第一个参数的bucketName属性来分配局部变量bucketName。在这种情况下,您要传递字符串文字-字符串文字没有bucketName属性。因此,您实际上是将undefined传递给storage.createBucket()。要解决此问题,只需除去括号即可,这样就不会破坏字符串的准确性:

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