直接从 google 存储读取 JSON 文件(使用 Cloud Functions)

Read JSON file directly from google storage (using Cloud Functions)

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

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

return result;

最终,我想直接从云存储中读取这个文件,这里我尝试了几种解决方案,但都没有成功。我怎样才能直接从 google 存储中读取 JSON 文件,以便像第一种情况一样,我可以正确读取它的属性?

如评论中所述,云存储 API 允许您通过 API 做很多事情。以下是 documentation 中关于如何从云存储下载文件的示例,供您参考。

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

明确回答问题:你不能!

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

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

  • 大小受限于为云函数设置的内存。内存 space 由您的应用程序内存占用和 /tmp 中的文件存储共享(例如,您将无法下载 10Gb 的文件)
  • 实例宕机时内存丢失
  • 所有 Cloud Functions 实例都有自己的内存 space。您不能在所有 Cloud Functions 之间共享文件
  • /tmp 目录在 2 个函数调用之间(在同一实例上)未被清除。考虑自己清理这个目录。