Search code examples
firebasegoogle-cloud-platformgoogle-cloud-storagefirebase-storagefirebase-admin

Uploading fire to Firebase Storage using firebase-admin in Node


I need to upload a file from a Node script to my Firebase storage using firebase-admin.

This is how I'm doing in the browser: (IT WORKS)

// THIS IS INSIDE A FUNCTION
const storageRef = firebase.storage().ref('my-images/' + fileName);
const uploadTask = storageRef.put(file,metadata);

This is how I'm TRYING to do in the Node script:

const admin = require('firebase-admin');
admin.initializeApp();

// THIS IS INSIDE A FUNCTION
const storageRef = admin.storage().ref('my-images/' + fileName);
const uploadTask = storageRef.put(file,metadata);

And I'm getting the error:

TypeError: admin.storage(...).ref is not a function

I also tried:

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  storageBucket: "MY_BUCKET.appspot.com"
});

// THIS IS INSIDE A FUNCTION
const storageRef = admin.storage().bucket().ref('my-images/' + fileName);
const uploadTask = storageRef.put(file,metadata);

And I'm getting the error:

TypeError: admin.storage(...).bucket(...).ref is not a function

QUESTION

I need to save the file in my default bucket inside the my-images folder. What is the proper way of doing it?


Solution

  • With the Google Cloud Storage Node.js Client you need to use a different approach compare to the JavaScript SDK.

    More precisely, you need to use the upload() method of a Bucket, as follows:

    bucket.upload('my-images/' + fileName).then(function(data) {
      const file = data[0];
    });
    

    You will find more example in the documentation (link above)