You can trigger a function in response to the uploading, updating, or deleting of files and folders in Cloud Storage.
Examples in this page are based on a sample function that triggers when image files are uploaded to Cloud Storage. This sample function demonstrates how to access event attributes, how to download a file to a Cloud Functions instance, and other fundamentals of handling Cloud Storage events.
Trigger a function on Cloud Storage changes
Use the firebase-functions/v2/storage
subpackage
to create a function that handles
Cloud Storage events. Depending on whether you want to scope your
function to a specific Cloud Storage bucket or use the default
bucket, use one of the following patterns:
// scope handler to a specific bucket, using a string parameter
export archivedbucket = onObjectArchived("myBucket", (event) => {
//…
});
// scope handler to a specific bucket, using storage options parameter
export archivedopts = onObjectArchived({ bucket: "myBucket" }, (event) => {
//…
});
By contrast, this thumbnail generator function is scoped to the default bucket for the project:
exports.generateThumbnail = onFinalize({ cpu: 2 }, async (event) => { // ... });
Setting the function location
Distance between the location of a Cloud Storage bucket and the location of the function can create significant network latency. Also, a mismatch between locations can result in deployment failure. To avoid these situations, specify the function location so that it matches the bucket/trigger location in one of these ways:
- Function location is the same as the trigger location
- Function location is inside the trigger location (when the trigger region is dual/multi region)
- Function may be in any location if the trigger region is set to
us-central1
Handling Cloud Storage events
Cloud Storage supports these events:
These handlers for responding to Cloud Storage events are available:
onObjectArchived
Only sent when a bucket has enabled object versioning. This event indicates that the live version of an object has become an archived version, either because it was archived or because it was overwritten by the upload of an object of the same name.onObjectDeleted
Sent when an object has been permanently deleted. This includes objects that are overwritten or are deleted as part of the bucket's lifecycle configuration. For buckets with object versioning enabled, this is not sent when an object is archived (seeonArchive
), even if archival occurs via thestorage.objects.delete
method.onObjectFinalized
Sent when a new object (or a new generation of an existing object) is successfully created in the bucket. This includes copying or rewriting an existing object. A failed upload does not trigger this event.onMetadataUpdated
Sent when the metadata of an existing object changes.
Access Cloud Storage object attributes
Cloud Functions exposes a number of Cloud Storage object attributes such
as
size
and
contentType
for the file updated. The
metageneration
attribute is incremented whenever there's a change to the
object's metadata. For new objects, the metageneration
value is 1
.
const fileBucket = event.data.bucket; // Storage bucket containing the file. const filePath = event.data.name; // File path in the bucket. const contentType = event.data.contentType; // File content type.
The thumbnail generation sample uses some of these attributes to detect exit cases in which the function returns:
// Exit if this is triggered on a file that is not an image. if (!contentType.startsWith('image/')) { return logger.log('This is not an image.'); } // Exit if the image is already a thumbnail. const fileName = path.basename(filePath); if (fileName.startsWith('thumb_')) { return logger.log('Already a Thumbnail.'); }
Download, transform, and upload a file
For some cases, it may not be necessary to download files from Cloud Storage. However, to perform intensive tasks such as generating a thumbnail image from a file stored in Cloud Storage, you need to download files to the functions instance—that is, the virtual machine that runs your code.
To easily download and re-upload objects to Cloud Storage, install the
Google Cloud Storage
package using
npm install --save @google-cloud/storage
, and import it. To use JavaScript
promises to handle external processes like the thumbnail processing tasks in the
sample, also import child-process-promise
:
const {onFinalize} = require('firebase-functions/v2/storage'); const {initializeApp} = require('firebase-admin/app'); const {getStorage} = require('firebase-admin/storage'); const logger = require('firebase-functions/logger'); const spawn = require('child-process-promise').spawn; const path = require('path'); const os = require('os'); const fs = require('fs'); initializeApp()
Use gcs.bucket.file(filePath).download
to download a file to a temporary
directory on your Cloud Functions instance. In this location, you can
process the file as needed and then upload to Cloud Storage. When
performing asynchronous tasks, make sure you return a JavaScript promise in your
callback.
Example: image transformation
Cloud Functions provides an image-processing program called
ImageMagick
that can perform
manipulations on graphical image files. The following is an example of how to
create a thumbnail image for an uploaded image file:
// Download file from bucket. const bucket = getStorage().bucket(fileBucket); const tempPath = path.join(os.tmpdir(), fileName); await bucket.file(filePath).download({destination: tempPath}); logger.log('Image downloaded locally to', tempPath); // Generate a thumbnail using ImageMagick. await spawn('convert', [tempPath, '-thumbnail', '200x200>', tempPath]); logger.log('Thumbnail created at', tempPath); // Prefix 'thumb_' to file name. const thumbFileName = `thumb_${fileName}`; const thumbFilePath = path.join(path.dirname(filePath), thumbFileName); // Uploading the thumbnail. const metadata = { contentType: contentType }; await bucket.upload(tempPath, { destination: thumbFilePath, metadata: metadata, }); // Once the thumbnail has been uploaded delete the local file to free up disk space. return fs.unlinkSync(tempPath);
This code executes the ImageMagick
command line program convert
to create a
200x200 thumbnail for the image saved in a temporary directory, then uploads it
back to Cloud Storage.
See the full Google Cloud Storage trigger documentation for more information.