首页 > 解决方案 > 在由 onFinalize 触发的 Firebase 云函数中获取已创建文件的兄弟姐妹

问题描述

我有一个在 firebase 存储中创建新文件时触发的云功能。在这个函数逻辑中,我需要收集位于数组中同一路径的所有其他文件。但我不知道怎么做。

exports.testCloudFunc = functions.storage.object().onFinalize(async object => {
  const filePath = object.name;

  const { Logging } = require('@google-cloud/logging');

  console.log(`Logged: ${filePath}`);
  let obj = JSON.stringify(object);
  console.log(`Logged: ${obj}`);
});

之后,我将尝试将所有 PDF 合并到一个新文件中,并通过相同的路径将其保存回 Firebase 存储。任何帮助都非常感谢!提前感谢您的智慧)

标签: javascriptfirebasevue.jsgoogle-cloud-platformgoogle-cloud-functions

解决方案


根据Doug Stevenson链接的文档 (Node.js 的第二个代码示例),您可以使用prefixesdelimiters列出存储桶中指定文件夹中的对象。

来自上述文档的示例:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const prefix = 'Prefix by which to filter, e.g. public/';
// const delimiter = 'Delimiter to use, e.g. /';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listFilesByPrefix() {
  /**
   * This can be used to list all blobs in a "folder", e.g. "public/".
   *
   * The delimiter argument can be used to restrict the results to only the
   * "files" in the given "folder". Without the delimiter, the entire tree under
   * the prefix is returned. For example, given these blobs:
   *
   *   /a/1.txt
   *   /a/b/2.txt
   *
   * 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
   */
  const options = {
    prefix: prefix,
  };

  if (delimiter) {
    options.delimiter = delimiter;
  }

  // Lists files in the bucket, filtered by a prefix
  const [files] = await storage.bucket(bucketName).getFiles(options);

  console.log('Files:');
  files.forEach(file => {
    console.log(file.name);
  });
}

listFilesByPrefix().catch(console.error);

这是否意味着所有文件将首先返回,然后将按前缀过滤?

正如我在上面的代码示例中看到的,数组[files]将存储已经通过过滤器要求的对象:

const [files] = await storage.bucket(bucketName).getFiles(options);

推荐阅读