簡體   English   中英

從 Firebase Cloud Function 在 Google Cloud Bucket 中創建文件

[英]Create File in Google Cloud Bucket from Firebase Cloud Function

我有一個 function 監控實時數據庫中的節點,一旦將新子節點寫入該節點,function 只需要在 Google 雲存儲桶中創建 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 錯誤所以我懷疑嘗試使用 upload()方法也會遇到同樣的問題。

我正在使用 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"
}

任何建議都是最受歡迎的

在每種情況下,您都沒有正確使用 Promise。 對於數據庫觸發器(和所有其他后台觸發器),您必須 返回一個 promise,當 function 中的所有異步工作完成時,它會解析。 現在,您根本沒有對 Promise 做任何事情,而您調用的每個 API 都是異步的。 您的 function 只是立即返回 0 而無需等待上傳完成,而 Cloud Functions 只是在任何事情發生之前終止和清理。

我建議選擇一種在上傳完成時返回 promise 的方法(可能是file.save() ),然后從 function 中返回 promise。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM