如何在 Cloud Functions 中访问云存储

Posted

技术标签:

【中文标题】如何在 Cloud Functions 中访问云存储【英文标题】:How To Access Cloud Storage In Cloud Functions 【发布时间】:2021-03-07 00:25:49 【问题描述】:

我试图在我的云函数中访问 Firebase 云存储,但我在云函数日志中不断收到以下错误:

Error: Failed to import the Cloud Storage client library for Node.js. Make sure to install the "@google-cloud/storage" npm package. Original error: SyntaxError: Unexpected token 
    at new FirebaseError (/srv/node_modules/firebase-admin/lib/utils/error.js:43:28)
    at new Storage (/srv/node_modules/firebase-admin/lib/storage/storage.js:65:19)
    at /srv/node_modules/firebase-admin/lib/firebase-app.js:255:20
    at FirebaseApp.ensureService_ (/srv/node_modules/firebase-admin/lib/firebase-app.js:376:23)
    at FirebaseApp.storage (/srv/node_modules/firebase-admin/lib/firebase-app.js:253:21)
    at FirebaseNamespace.fn (/srv/node_modules/firebase-admin/lib/firebase-namespace.js:292:45)
    at exports.initializeNewVideoUpload.functions.firestore.document.onCreate (/srv/index.js:383:24)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:134:23)
    at /worker/worker.js:825:24
    at <anonymous>

下面是我的代码:

const admin = require('firebase-admin'); const functions = require('firebase-functions');

admin.initializeApp();
const db = admin.firestore();
exports.initializeNewVideoUpload = functions.firestore.document('new-videos-uploads/id').onCreate(async (snapshot, context) => 
      const data = snapshot.data();
      const fileNames = data.file_names;
      const bucket = admin.storage().bucket('trumateappdev.appspot.com');
    
      fileNames.forEach(async fileName => 
        const actualFile = bucket.file(fileName);
        const resumableUpload = await actualFile.createResumableUpload();
        const uploadEndpointUrl = resumableUpload[0];
    
        data.resumable_urls.push(uploadEndpointUrl);
      );
    
      await admin.firestore().collection('new-videos-uploads').doc(context.params.id).update(data);
    );

以下是我的 package.json 中的依赖项:

"@google-cloud/storage": "^5.5.0",
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0"

PS:我在 Spark 计划中

【问题讨论】:

请编辑问题以显示complete minimal example 重现问题。问题中应该有足够的信息,任何人都可以复制并重现问题。 【参考方案1】:

我找到了这个解决方案here。将此添加到您的package.json

"engines": "node": "8"

显然这个问题是因为你的node.js版本太旧了

【讨论】:

记得编辑package.json后运行npm install

以上是关于如何在 Cloud Functions 中访问云存储的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Cloud Functions 将文件上传到 Cloud Storage 并使用 Firestore 控制对 Cloud Storage 的访问?

Cloud Functions:如何上传附加文件以在代码中使用?

在 Cloud Functions for Firebase 中访问 db 数据

如何在 Google Cloud Functions 的 python 环境中检查 HTTP 基本身份验证

从 Google Cloud Functions 控制台中访问 MongoDB Atlas 集群

具有 Google Cloud Functions 的 Google Cloud Endpoints [关闭]