Node.js 直接从google存储读取JSON文件(使用云函数)

Node.js 直接从google存储读取JSON文件(使用云函数),node.js,google-cloud-platform,google-cloud-storage,Node.js,Google Cloud Platform,Google Cloud Storage,我创建了一个从JSON文件中提取特定属性的函数,但该文件与云函数中的函数一起使用。在本例中,我只是附加了文件,并且能够引用特定属性: const jsonData = require('./data.json'); const result = jsonData.responses[0].fullTextAnnotation.text; return result; 最终,我想直接从云存储读取此文件,在这里我尝试了几种解决方案,但没有成功。如何直接从google storage中读取JSON

我创建了一个从JSON文件中提取特定属性的函数,但该文件与云函数中的函数一起使用。在本例中,我只是附加了文件,并且能够引用特定属性:

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

return result;

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

如注释中所述,云存储API允许您通过API执行许多操作。下面是一个关于如何从云存储下载文件供您参考的示例

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

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

您需要首先在本地下载该文件,然后对其进行处理。你不能直接从地面军事系统读到它

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

  • 大小受为云函数设置的内存限制。内存空间在应用程序内存占用空间和
    /tmp
    中的文件存储空间之间共享(例如,您将无法下载10Gb的文件)
  • 当实例停止运行时,内存将丢失
  • 所有云函数实例都有自己的内存空间。您不能在所有云函数之间共享文件
  • /tmp
    目录未在两个函数调用之间清理(在同一实例上)。考虑清理这个目录

在云存储中读取文件有许多不同语言的教程和示例。显示您尝试的内容、代码和错误。