从Firebase Cloud Function在Google Cloud Bucket中创建文件

编程入门 行业动态 更新时间:2024-10-07 12:23:04

从Firebase Cloud Function在Google Cloud Bucket中创建<a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件"/>

从Firebase Cloud Function在Google Cloud Bucket中创建文件

我有一个监视实时数据库中节点的函数,一旦有新的子节点写入该节点,该函数只需要在Google Cloud存储桶中创建一个html文档。 HTML文档将具有唯一的名称,并将包含来自该节点的一些数据。一切都很简单,但是我实际上无法创建和写入文档。到目前为止,我已经尝试了3种方法(在下面的代码中概述),这些方法都不起作用。

const {Storage} = require('@google-cloud/storage');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const fs = require('fs');
const {StringStream} = require('@rauschma/stringio')

const instanceId = 'my-project-12345';
const bucketName = 'my-bucket';

exports.processCertification = functions.database.instance(instanceId).ref('/t/{userId}/{testId}')
    .onCreate((snapshot, context) => {
      const dataJ = snapshot.toJSON();

      var testResult = "Invalid";
      if(dataJ.r == 1) {testResult = "Positive";}
      else if(dataJ.r == 2) {testResult = "Negative";}

      console.log('Processing certificate:', context.params.testId, testResult);

      var storage = new Storage({projectId: instanceId});
      const fileName = context.params.testId + '.html';
      const fileContents = "<html><head></head><body>Result: " + testResult + "</body></html>"
      const options = {resumable:false, metadata:{contentType:'text/html'}};

      const bucket = storage.bucket(bucketName);
      const file = bucket.file(fileName);

      console.log('Saving to:' + bucketName + '/' + fileName);

      if(false) {
        // Test 1. the file.save method
        // Errors with:
        //  (node:2) MetadataLookupWarning: received unexpected error = URL is not defined code = UNKNOWN
        file.save(fileContents, options, function(err) {
          if (!err) {console.log("Save created object at " + bucketName + "/" + fileName);}
          else {console.log("Save Failed " + err);}
        });

      } else if(true) {
        // Test 2. the readStream.pipe method
        // No errors, doesn't output error message, doesn't output finish message, no file created
        fs.createReadStream(fileContents)
          .pipe(file.createWriteStream(options))
          .on('error', function(err) {console.log('WriteStream Error');})
          .on('finish', function() {console.log('WriteStream Written');});

      } else {
        // Test 3. the StringStream with readStream.pipe method
        // Errors with:
        //   (node:2) MetadataLookupWarning: received unexpected error = URL is not defined code = UNKNOWN
        const writeStream = storage.bucket(bucketName).file(fileName).createWriteStream(options);
        writeStream.on('finish', function(){console.log('WriteStream Written');}).on('error', function(err){console.log('WriteStream Error');});
        const readStream = new StringStream(fileContents);
        readStream.pipe(writeStream);

      }
      console.log('Function Finished');

      return 0;
    });

在所有情况下,都会出现“正在处理证书”和“保存到”输出,每次我也收到“功能已完成”消息。错误(或者在某种情况下没有响应)针对代码中的每个测试编写。

我的下一步是在本地创建文件,然后使用upload()方法,但是这些方法中的每一种似乎都应该起作用,再加上我仅有的错误消息是关于URL错误的信息,所以我怀疑尝试使用上载()方法也会遇到相同的问题。

我正在使用Node.JS v8.17.0和以下软件包

"dependencies": {
  "@google-cloud/storage": "^5.0.0",
  "@rauschma/stringio": "^1.4.0",
  "firebase-admin": "^8.10.0",
  "firebase-functions": "^3.6.1"
}

欢迎任何意见

回答如下:

在每种情况下,您都无法正确使用诺言。对于数据库触发器(和所有其他背景触发器),必须在函数中return a promise that resolves when all of the asynchronous work is complete。现在,您没有对诺言做任何事情,而您正在调用的每个API都是异步的。您的函数只是立即返回0,而无需等待上传完成,而Cloud Functions只是在发生任何事情之前终止并清理掉。]

我建议选择一种返回上载承诺的方法完成(可能是file.save()),然后从函数中返回该承诺。

更多推荐

从Firebase Cloud Function在Google Cloud Bucket中创建文件

本文发布于:2024-05-07 20:41:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757156.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   Cloud   Firebase   Function   Bucket

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!