Skip to content

Instantly share code, notes, and snippets.

@kingychiu
Last active May 31, 2019 16:50
Show Gist options
  • Save kingychiu/75871accde89833bfb86646b217a3d9f to your computer and use it in GitHub Desktop.
Save kingychiu/75871accde89833bfb86646b217a3d9f to your computer and use it in GitHub Desktop.
Example Code For Backing Up Google Cloud Storage with Cloud Functions
/***
package.json:
{
"name": "sample-pubsub",
"version": "0.0.1",
"dependencies": {
"@google-cloud/pubsub": "^0.18.0",
"firebase-admin": "8.0.0"
}
}
***/
const admin = require('firebase-admin');
admin.initializeApp();
const sourceBucket = admin.storage().bucket("test-product-bucket");
const destBucket = admin.storage().bucket("test-back-up-bucket");
exports.helloPubSub = async (event, context) => {
console.log("backup started")
const d = new Date();
const dateStr = d.toLocaleDateString();
console.log(dateStr);
const [sourceFiles] = await sourceBucket.getFiles({
prefix: 'data/'
});
const sourceFileNames = sourceFiles.map(
(file) => file.name);
console.log(dateStr, "# Total", sourceFileNames.length);
let promises = [];
for (let fileName of sourceFileNames) {
const copyFilePromise = sourceBucket.file(fileName).copy(destBucket.file(`${dateStr}/${fileName}`));
promises.push(copyFilePromise);
}
await Promise.all(promises);
console.log("backup ended")
return "DONE";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment