はじめに
Firebaseのプロジェクトを作り直した際、元のプロジェクトから新しいプロジェクトへStorageの中身を全てコピーする必要がありました。調べたけど複数ファイルを一括で扱う方法が見つからなかったので、forEachで1ファイルずつ処理しました。
Google Cloud Storageからのダウンロード
Storage直下にあるファイルをローカルのworkディレクトリへダウンロードします。
download-storage.js
const admin = require('firebase-admin');
const serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: "<BUCKET_NAME>.appspot.com"
});
const bucket = admin.storage().bucket();
async function main() {
const files = await bucket.getFiles();
files[0].forEach((file) => {
const filePath = `./work/${file.name}`;
console.log(filePath);
file.download({destination: filePath});
});
}
main().then();
Google Cloud Storageへのアップロード
ローカルのworkディレクトリにあるファイルをStorage直下へアップロードします。
upload-storage.js
const fs = require('fs');
const admin = require('firebase-admin');
const serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: "<BUCKET_NAME>.appspot.com"
});
const bucket = admin.storage().bucket();
async function main() {
const files = await fs.readdirSync('./work');
files.forEach((file) => {
const filePath = `./work/${file}`;
console.log(filePath);
bucket.upload(filePath);
});
}
main().then();