【问题标题】:Google Storage is not a constructor errorGoogle Storage 不是构造函数错误
【发布时间】:2019-02-11 20:25:42
【问题描述】:

我正在构建一个应用程序,我的目标是每次有人将图像上传到 Firebase 存储时,云功能都会调整该图像的大小。

...
import * as Storage from '@google-cloud/storage'
const gcs = new Storage()
...

exports.resizeImage = functions.storage.object().onFinalize( async object => {
   const bucket = gcs.bucket(object.bucket);
   const filePath = object.name;
   const fileName = filePath.split('/').pop();
   const bucketDir = dirname(filePath);
....

当我尝试部署这个功能时,我得到了这个错误:

Error: Error occurred while parsing your function triggers.

TypeError: Storage is not a constructor

我尝试使用“new Storage()”或仅使用“Storage”,但没有任何效果。

我是这里的新手,所以如果有什么我忘了让你调试,请告诉我。

谢谢!


谷歌云/存储:2.0.0

节点js:v8.11.4

【问题讨论】:

    标签: node.js firebase google-cloud-storage google-cloud-functions


    【解决方案1】:

    API documentation for Cloud Storage 建议你应该使用 require 来加载模块:

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

    这适用于 2.x 版之前的 Cloud Storage 版本。

    在 2.x 中,API 发生了重大变化。您现在需要这样做:

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

    如果您需要 TypeScript 绑定,请考虑通过 Firebase Admin SDK 使用 Cloud Storage。 The Admin SDK simply wraps the Cloud Storage module,并且还导出类型绑定以配合它。使用方便:

    import * as admin from 'firebase-admin'
    admin.initializeApp()
    admin.storage().bucket(...)
    

    admin.storage() 为您提供了对您尝试使用的 Storage 对象的引用。

    【讨论】:

    • 像魅力一样工作!喜欢你的教程,非常感谢!
    • 顺便提一下,@google-cloud/storage 的 2.x 版本要求您现在执行此操作:const { Storage } = require(...)
    • 我不得不使用它并将我的令牌传递给构造函数const storage = new Storage({ keyFilename: "jorge-dashboard-v1-9dcf1f36dd34.json" });
    【解决方案2】:

    如果你们使用 ES 模块方法和节点 12,仅出于知识目的,下面的 sn-p 将起作用。我无法让其他语法都不起作用~

    import storagePackage from '@google-cloud/storage';
    const { Storage } = storagePackage;
    const storage = new Storage();
    

    【讨论】:

      【解决方案3】:

      在节点 14 上,将 commonJS 与 babel 一起使用(尽管我认为 Babel 并没有干扰这里),这就是我最终在一个将 GCS 从 1.x 升级到 5.x 的旧项目中使用它的方式:

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

      在网络上的任何地方都没有看到这个捕获

      【讨论】:

        【解决方案4】:

        如果您正在使用电子,但仍然无法使用上述解决方案,请试试这个。

        const {Storage} = window.require('@google-cloud/storage');
        const storage = new Storage({ keyFilename: "./uploader-credentials.json" });
        

        【讨论】:

        • OP 已经接受了一个答案并在comment 中写道,三年前,它已经解决了......
        • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
        • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-27
        • 2019-08-11
        • 2022-06-11
        • 2012-06-09
        • 1970-01-01
        • 2018-01-23
        相关资源
        最近更新 更多