JustinMartinDev
JustinMartinDev

Reputation: 639

Firebase storage - Download directory as ".zip"

If you use firebase storage, you could see it's not possible to download a folder (as zip) directly from firebase UI or using gcloud UI. So it can be hard to create backup of your firebase storage bucket, moreover if you use firestore you can export collections into firebase storage.

Upvotes: 1

Views: 2571

Answers (1)

JustinMartinDev
JustinMartinDev

Reputation: 639

I created a nodejs script based on firebase-admin and jszip, with two args : first the download path in firebase storage and second is the path where stored the zip file

package.json:

{
  "dependencies": {
    "firebase-admin": "^9.6.0",
    "jszip": "^3.6.0"
  }
}

index.js:

const fs = require("fs");
const JSZip = require('jszip');
const admin = require('firebase-admin');

const serviceAccount = require("./service-account-key.json");

async function main (){
    try{
        admin.initializeApp({
            credential: admin.credential.cert(serviceAccount),
            storageBucket: "stackd-56e96.appspot.com",
        });
        const bucket = admin.storage().bucket();

        const src_storage_path = process.argv[2];
        let dest_storage_path = process.argv[3];

        if(dest_storage_path.includes(":"))
            dest_storage_path = dest_storage_path.replace(":", "_")

        const jszip = new JSZip();
        const files = (await bucket.getFiles({
            prefix: `${src_storage_path}/`
        }))[0]

        const filesContent = await Promise.all(
            files.map(file => file.download())
        );

        filesContent.forEach((content, i) => {
            jszip.file(files[i].name, content[0])
        });

        const content = await jszip.generateAsync({ type: 'nodebuffer' });

        await fs.promises.writeFile(dest_storage_path, content)
    } catch (error){
        console.error(error)
    }
}

main();

command line exemple:

node index.js 2021-04-16T11:47:46_54052 backup.zip

enter image description here

Upvotes: 4

Related Questions