首页 > 解决方案 > 直接从谷歌存储读取 JSON 文件(使用 Cloud Functions)

问题描述

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

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

return result;

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

标签: node.jsgoogle-cloud-platformgoogle-cloud-storage

解决方案


正如评论中提到的,云存储 API 允许您通过 API 做很多事情。以下是有关如何从 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);

推荐阅读