0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Firebase Storageの複数ファイルをダウンロード&アップロード

Posted at

はじめに

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();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?