Node.js Cloud Function - 将 CSV 数据直接流式传输到 Google Cloud Storage 文件

Node.js Cloud Function - Stream CSV data directly to Google Cloud Storage file

我有一个脚本可以调用 RESTful API 并从报告中分块检索 CSV 数据。我能够在控制台中连接、解析和显示这些数据。我还可以将此 CSV 数据写入本地文件并存储。

我想弄清楚的是如何在将数据上传到 GCS 之前跳过创建文件来存储这些数据,而是直接将其传输到 Google 云存储以另存为文件。由于我试图使它成为一个无服务器云函数,我试图将它直接从内存流式传输到 Google 云存储文件中。

我在 Stack overflow 上找到了这个 'Streaming Transfers' documentation on google, but it only references doing this with 'gsutil' and I am struggling to find any examples or documentation on how to do this with node.js. I also tried to follow this answer,但它是 2013 年的,方法似乎有点过时了。我的脚本也不面向用户,所以我不需要点击任何路由。

我可以使用以下功能将本地文件直接上传到我的存储桶,因此身份验证不是问题。我只是不确定如何将内存中的 CSV blob 或对象转换为 GCS 中的文件。我没能找到很多例子,所以不确定过去是否有其他人解决过这个问题。

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({
  projectId,
  keyFilename
 });

function uploadCSVToGCS() {
   const localFilePath = './test.csv';
   const bucketName = "Test_Bucket";
   const bucket = storage.bucket(bucketName);

   bucket.upload(localFilePath);
};

我还发现了一个 Google 引用的名为 'boto' 的第 3 方插件,它似乎可以满足我的要求,但不幸的是,这是 python 而不是 node.js .

将对象数据流式传输到 Cloud Storage 在 documentation. You will need to understand how node streams work, and make use of createWriteStream 中进行了说明。示例代码不是您想要的,但您将使用相同的模式:

function sendUploadToGCS (req, res, next) {
  if (!req.file) {
    return next();
  }

  const gcsname = Date.now() + req.file.originalname;
  const file = bucket.file(gcsname);

  const stream = file.createWriteStream({
    metadata: {
      contentType: req.file.mimetype
    },
    resumable: false
  });

  stream.on('error', (err) => {
    req.file.cloudStorageError = err;
    next(err);
  });

  stream.on('finish', () => {
    req.file.cloudStorageObject = gcsname;
    file.makePublic().then(() => {
      req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
      next();
    });
  });

  stream.end(req.file.buffer);
}

@doug-stevenson 感谢您将我推向正确的方向。我能够使用以下代码让它工作:

const { Storage } = require('@google-cloud/storage');
const storage = new Storage();
const bucketName = 'test_bucket';
const blobName = 'test.csv';
const bucket = storage.bucket(bucketName);
const blob = bucket.file(blobName);
const request = require('request');


function pipeCSVToGCS(redirectUrl) {
      request.get(redirectUrl)
      .pipe(blob.createWriteStream({
          metadata: {
              contentType: 'text/csv'
          }
      }))
    .on("error", (err) => {
        console.error(`error occurred`);
    })
    .on('finish', () => {
        console.info(`success`);
    });
};