Similarly, Cloud Functions can also be triggered by changes in Cloud Storage buckets:
- Write the Cloud Function and save it as index.js:
/**
* Background Cloud Function to be triggered by Cloud Storage..
*/
exports.helloGCS = function (event, callback)
{
const file = event.data;
if (file.resourceState === 'not_exists')
{
console.log(`File ${file.name} deleted.`);
}
else if (file.metageneration === '1')
{
// metageneration attribute is updated on metadata changes.
// on create value is 1
console.log(`File ${file.name} uploaded.`);
}
else
{
console.log(`File ${file.name} metadata updated.`);
}
callback();
};
- Deploy the Cloud Function:
gcloud beta functions deploy helloGCS --trigger-bucket <BUCKET_NAME>
- Trigger (invoke) the Cloud Function
- As before, we can invoke this function either by uploading a file (say test.txt) to the bucket, or through an equivalent direct invocation:
gcloud beta functions call helloGCS --data '{"name":"test.txt"}'
Once invoked, the logs should contain the log entry stating that test.txt file was uploaded to the GCS bucket.