Domingos Nunes
Domingos Nunes

Reputation: 132

Google Storage is not a constructor error

I am building an App and my objective is every time someone upload an image to firebase storage, the cloud function resize that image.

...
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);
....

And when I tried to deploy this funtion I get this error:

Error: Error occurred while parsing your function triggers.

TypeError: Storage is not a constructor

I tried with "new Storage()" or just "Storage" and nothing works.

I'm newbie around here so if there's anything I forgot for you to debug this just let me know.

Thanks!


google-cloud/storage: 2.0.0

Node js: v8.11.4

Upvotes: 11

Views: 8016

Answers (4)

Dilan Perera
Dilan Perera

Reputation: 1

If you are using electron and still don't work above solutions,try this.

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

Upvotes: 0

Jakay
Jakay

Reputation: 23

On node 14, using commonJS with babel (although I don't think Babel was interfering here), this is how I eventually got it working on an older project bumping GCS from 1.x to 5.x:

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

didn't see this captured anywhere on the web

Upvotes: 1

Ahsan.Amin
Ahsan.Amin

Reputation: 774

Just for knowledge purpose if you guys are using the ES module approach and node 12, the below snippet would work. I couldn't make none of other syntax working~

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

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317372

The API documentation for Cloud Storage suggests that you should use require to load the module:

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

This applied to versions of Cloud Storage prior to version 2.x.

In 2.x, there was a breaking API change. You need to do this now:

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

If you would like TypeScript bindings, consider using Cloud Storage via the Firebase Admin SDK. The Admin SDK simply wraps the Cloud Storage module, and also exports type bindings to go along with it. It's easy to use:

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

admin.storage() gives you a reference to the Storage object that you're trying to work with.

Upvotes: 30

Related Questions