如何使用 Firebase Functions 获取存储桶中的文件列表

How can I get a list of files in my storage bucket using Firebase Functions

我正在尝试编写一个简单的函数,该函数将使用 Firebase 云函数迭代我在 Firebase 存储文件夹中的所有文件。我花了几个小时在线尝试每个示例并阅读文档。

这是我目前拥有的:

exports.removeUnsizedImages = functions.pubsub.schedule('every 2 minutes').onRun((context) => {

    const storage = admin.storage();
    var storageRef = storage.ref();

    storageRef.listAll().then(function(result) {
        console.log("*", result);
    })
});

我收到一个错误,提示 storage.ref() 不是一个函数。

如果我尝试:

storage.listAll()

它还告诉我 listAll 不是函数。

我真的没想到把文件放在一个文件夹里这么难。

我做错了什么?

现在可用的更新代码

exports.removeUnsizedImages = functions.pubsub.schedule('every 24 hours').onRun((context) => {
    
    admin.storage().bucket().getFiles({ prefix: "postImages/" }).then(function(data) {
        const files = data[0];

        files.forEach(function(image) {
            console.log("***** ", image.name)
        })

    });
    
});

您使用的 listAll 是 Firebase 存储客户端 SDK 中的一个函数,而不是 Admin SDK 中的函数。

要获取 Admin SDK 中的所有文件,试试这个:

const allFiles = await admin.storage().bucket().getFiles({ prefix: "/user/images" })

Here prefix is the path which you want to list.

  • If you just specify prefix = 'a/', you'll get back:
  • /a/1.txt
  • /a/b/2.txt
  • However, if you specify prefix='a/' and delimiter='/', you'll get back:
  • /a/1.txt

您只需使用 .getFiles() 即可获得整个存储桶。可以在 documentation

中找到更多详细信息