I have a project that uses Firebase tools to store images in Firebase Storage and various data in the Realtime Database.
I have a cloud function that is triggered with a Database change. Inside this function I need to access a specific file's metadata to fetch some information (I do not need to modify the metadata).
This is how I access the file.
const gcs = require('@google-cloud/storage')();
...
const bucket = admin.storage().bucket();
...
myFile = bucket.file("images/" + imagePath);
How do I get the metadata? Naive solutions like these:
myFile.metadata;
or
myFile.getMetadata();
do not work. I assume there should be an easy built-in method and was very surprised to find it extremely hard to find a solution online.
According to the documentation (Client API Reference for the Google Cloud Storage Node.js Client), you should use getMetadata()
, as follows:
const gcs = require('@google-cloud/storage')();
...
const bucket = admin.storage().bucket();
...
myFile = bucket.file("images/" + imagePath);
myFile.getMetadata().then(function(data) => {
const metadata = data[0].metadata;
});
Note that it is also possible to call this method as follows: myFile.getMetadata(function(err, metadata, apiResponse) {});
.
However, since, in a Cloud Function you must return a Promise when performing asynchronous work (see why here), you should omit the callback and use the Promise that is returned by the method.