【问题标题】:Get siblings of created file in firebase cloud function triggered by onFinalize在由 onFinalize 触发的 Firebase 云函数中获取已创建文件的兄弟姐妹
【发布时间】:2020-05-17 10:52:05
【问题描述】:

我有一个云功能,当在 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 存储。任何帮助都非常感谢!提前感谢您的智慧)

【问题讨论】:

  • 使用 Cloud Storage 列表 API 列出具有通用路径前缀的文件。 cloud.google.com/storage/docs/listing-objects
  • 谢谢。我发现我可以像这样收集所有文件: const [files] = await storage.bucket(bucketName).getFiles();但是如何指定像 "bucketName/loads/" 这样的路径?
  • 查看文档中的第二个代码示例。
  • 是不是先返回所有文件,然后再按前缀过滤?

标签: javascript firebase vue.js google-cloud-platform google-cloud-functions


【解决方案1】:

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

示例来自上述文档:

/**
 * 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);

【讨论】:

    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2014-09-20
    • 2012-02-27
    • 2019-05-06
    相关资源
    最近更新 更多