【问题标题】:Read JSON file directly from google storage (using Cloud Functions)直接从谷歌存储读取 JSON 文件(使用 Cloud Functions)
【发布时间】:2021-05-11 15:25:47
【问题描述】:

我创建了一个从 JSON 文件中提取特定属性的函数,但该文件与 Cloud Functions 中的函数一起使用。在这种情况下,我只是附加文件并能够引用特定属性:

const jsonData = require('./data.json');
const result = jsonData.responses[0].fullTextAnnotation.text;

return result;

最终,我想直接从云存储中读取这个文件,在这里我尝试了几种解决方案,但都没有成功。如何直接从谷歌存储中读取 JSON 文件,以便像第一种情况一样正确读取其属性?

【问题讨论】:

  • 云存储中有大量的教程和多语种文件读取示例。显示您尝试过的内容、代码和错误。

标签: node.js google-cloud-platform google-cloud-storage


【解决方案1】:

正如评论中提到的,Cloud Storage API 允许您通过 API 做很多事情。以下是来自documentation 的示例,说明如何从 Cloud Storage 下载文件供您参考。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The path to which the file should be downloaded
// const destFileName = '/local/path/to/file.txt';

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

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

async function downloadFile() {
  const options = {
    destination: destFileName,
  };

  // Downloads the file
  await storage.bucket(bucketName).file(fileName).download(options);

  console.log(
    `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
  );
}

downloadFile().catch(console.error);

【讨论】:

    【解决方案2】:

    为了清楚地回答这个问题:你不能!

    您需要先将文件下载到本地,然后再进行处理。您不能直接从 GCS 读取它。

    使用 Cloud Functions,您只能将文件存储在 /tmp 目录中,这是唯一可写的。此外,它是一个内存文件系统,这意味着几件事:

    • 大小受云函数设置的内存限制。内存空间在您的应用内存占用和/tmp 中的文件存储之间共享(例如,您将无法下载 10Gb 的文件)
    • 当实例宕机时内存会丢失
    • 所有 Cloud Functions 实例都有自己的内存空间。您无法在所有 Cloud Functions 之间共享文件
    • /tmp 目录在 2 个函数调用之间未清理(在同一实例上)。想想自己清理这个目录。

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2018-02-28
      • 2018-01-27
      • 2023-03-30
      • 2021-12-23
      • 2021-07-30
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      相关资源
      最近更新 更多