我想运行一个Firebase Cloud Function调度程序,每天删除一次以.png
结尾的特定bucket中的所有文件。
这就是我尝试过的:
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
exports.scheduledFunctionCrontab = functions.pubsub.schedule('0 0 * * *')
.timeZone('Europe/Amsterdam')
.onRun((context) => {
console.log('This will be run every day at midnight in NL!');
const bucketName = '<myBucketName>'; //where I replaced this with my actual bucketname
const filename = '*.png';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
async function deleteFile() {
// Deletes the file from the bucket
await storage.bucket(bucketName).file(filename).delete();
console.log(`gs://${bucketName}/${filename} deleted.`);
}
deleteFile().catch(console.error);
return null;
});
但是我得到了一个message: 'No such object: <myBucketName>/*.png'
错误。JavaScript API似乎没有接收到*。使用gsutil,这个通配符确实有效。当我输入对象的全名时,它会根据计划的时间成功删除。
大多数云存储API都无法做到这一点。它们通常不支持通配符。gsutil
CLI正在为您进行文件匹配,但在某些情况下,它使用API并将结果匹配到*.png
。
因此,使用getFiles((并在代码中进行模式匹配,以创建匹配文件的列表。
好吧,根据@jarmod的信息,我更新了代码,并使其工作如下:
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
exports.scheduledFunctionCrontab = functions.pubsub.schedule('0 0 * * *')
.timeZone('Europe/Amsterdam')
.onRun((context) => {
console.log('This will be run every day at midnight in NL!');
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
const bucketName = '<myBucketName>'; //where I replaced this with my actual bucketname
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
async function deleteFile(filename) {
// Deletes the file from the bucket
await storage.bucket(bucketName).file(filename).delete();
console.log(`gs://${bucketName}/${filename} deleted.`);
}
async function listAndDeleteFiles() {
// Lists files in the bucket
const [files] = await storage.bucket(bucketName).getFiles();
console.log('Files:');
files.forEach(file => {
console.log(file.name);
if (file.name.endsWith(".png")) {
deleteFile(file.name);
}
});
}
listAndDeleteFiles().catch(console.error);
return null;
});