iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🗃️
Listing files in Cloud Storage for Firebase using firebase-admin
I wanted to use firebase-admin to get a list of files existing in an arbitrary directory of Cloud Storage for Firebase. However, even after reading the Official Admin Cloud Storage API Overview, I was at a loss regarding how to use it beyond admin.storage().bucket(). I am recording the results of my research here.
Use getFiles
For example, in a case where you want a list of images in gs://xxxxx.appspot.com/users/${uid}/photos/*.png, you can retrieve them by specifying xxxxx.appspot.com in the storageBucket of initializeApp and using bucket#getFiles with the directory specified as directory: users/${uid}/photos/.
From there, if you want the file URLs, use bucket#getSignedUrl.
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert(require(certFilePath)),
storageBucket: "xxxxx.appspot.com"
});
const bucket = admin.storage().bucket();
const files = await bucket.getFiles({
directory: `users/${uid}/photos/`
});
for (const item of files[0]) {
const url = await item.getSignedUrl({
action: 'read',
expires: '01-01-2021'
});
console.log(url);
}
Discussion