nodejs使用fire storage - DashingDigit001/WikiPage GitHub Wiki

  1. 安裝firebase-admin
  2. firebase console -> 左上角齒輪 -> 專案設定 -> 服務帳戶 -> 產生新的私密金鑰 -> 取名sakey.json
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    storageBucket: "<BUCKET_NAME>.appspot.com" 
});

//gs://miatreasure-fe805.appspot.com
var bucket = admin.storage().bucket();

使用範例

  • 取得所有檔案
async function listFiles() {
    // Lists files in the bucket
    try {
        const files = await bucket.getFiles();
        console.log("Files:");
        files[0].forEach((file) => {
            console.log(file.name);
        });
    } catch (e) {
        console.log(e);
    }
}
 
listFiles();
  • 將檔案變成public
let result = await bucket.file("bellauno/25607403-1.JPG").makePublic();
  • 取得url
const files = await bucket.getFiles();
        console.log("Files:");
        files[0].forEach((file) => {
            console.log(file.publicUrl());
        });