【问题标题】:Opening/Reading CSV file from Cloud Storage to Cloud Functions从 Cloud Storage 打开/读取 CSV 文件到 Cloud Functions
【发布时间】:2019-01-24 08:44:04
【问题描述】:

有没有办法从 Google Cloud Storage 中的 csv 文件读取和打印 Cloud Functions 中的数据?

Cloud Function API 文档仅说明了将对象下载到本地计算机的内容。

我正在对话流上创建一个实现,它将根据用户的查询通过云功能打开并读取云存储上的一些 CSV 文件。

【问题讨论】:

    标签: google-cloud-platform google-cloud-functions google-compute-engine dialogflow-es


    【解决方案1】:

    一般来说,您可以将云存储对象“下载”到 NodeJS 流或字符串,然后从该流或字符串解析 CSV。使用流更复杂,但最好是 CSV 非常大。如果您的 CSV 很小并且可以放入内存中,那么字符串会更容易。

    要获取数据,您可以使用Cloud Storage node.js library。特别是,您可以使用 File 对象的createReadStream() 方法或download() 方法分别获取流或字符串。

    一旦你有了它,你就可以使用 node.js 的 CSV Parse API 库。

    【讨论】:

    • 您是否必须使用任何 await 来等待文件流完成?
    • createReadStream() 是基于事件的,不使用异步/等待。 download() 返回一个 Promise,因此您可以在其上使用 await。如果您还有其他具体问题,您可能需要提出一个新问题,其中包含导致您出现问题的代码的详细信息和示例。
    【解决方案2】:

    如果您使用的是 Java,那么您可以使用 google-cloud-java 的本机 Java API (NIO) 来访问来自 Google Cloud Storage 的文件。有关文档,请参阅 this page

    【讨论】:

      【解决方案3】:
      async function getFileData() {
          const bucketName = 'bucket-name';
          const filePath = 'prefix/file-name.csv';
          const file = storage.bucket(bucketName).file(filePath);
      
          const csvData = await file.download().then(function(contents) {
              console.log("ASCII Contents", contents);
              return contents.toString('ascii');
          }).catch(function(error) {
              console.error("Error File Path:", filePath);
          });
          console.error("CSV File Content:", csvData);
      }
      
      getFileData().catch(console.error);
      

      【讨论】:

        猜你喜欢
        • 2019-04-08
        • 2020-03-07
        • 2019-09-27
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 2023-03-29
        • 2019-11-17
        • 1970-01-01
        相关资源
        最近更新 更多