【问题标题】:How to bundle and require non JS dependencies in Firebase Cloud Functions?如何在 Firebase Cloud Functions 中捆绑和要求非 JS 依赖项?
【发布时间】:2020-02-22 07:31:05
【问题描述】:

我有一个返回一些动态 HTML 的 http 云函数。我想使用 Handlebars 作为模板引擎。模板足够大,将它放在我的函数顶部的 const 变量中是不切实际的。

我尝试过类似的方法:

const template = fs.readFileSync('./template.hbs', 'utf-8');

但是在部署函数时,我总是得到一个文件不存在的错误:

Error: ENOENT: no such file or directory, open './template.hbs'

template.hbs 与我的 index.js 文件位于同一目录中,所以我想问题是 Firebase CLI 没有将此文件与其余文件捆绑在一起。

根据docs of Google Cloud Functions,可以将本地模块与"mymodule": "file:mymodule" 捆绑在一起。所以我尝试在项目的根目录下创建一个templates 文件夹,并将"templates": "file:./templates" 添加到package.json

我的文件结构是这样的:

/my-function
  index.js
/templates
  something.hbs
index.js //this is the entry point

然后:

const template = fs.readFileSync('../node_modules/templates/something.hbs', 'utf-8');

但我遇到了同样的未找到错误。

在 Firebase 云函数中包含和要求非 JS 依赖项的正确方法是什么?

【问题讨论】:

    标签: node.js firebase google-cloud-functions


    【解决方案1】:

    Firebase CLI 将打包所有函数文件夹中的文件,node_modules 除外,并将整个存档发送到 Cloud Functions。它将通过运行npm install 来重构 node_modules,同时构建运行您的函数的 docker 映像。

    如果您的 something.hbs 位于您的函数文件夹下的 /templates 中,您应该能够在顶级 index.js 中将其称为 ./templates/something.hbs。如果您的 JS 在另一个文件夹中,您可能必须先使用../templates/something.hbs 解决问题。文件应该都在那里——只要找出路径。我不会尝试做任何花哨的事情是你的 package.json。只需利用 CLI 部署除 node_modules 之外的所有内容这一事实。

    如果我的函数文件夹的根目录中有一个名为“foo”的文件,那么这段代码对我来说很好:

    import * as fs from 'fs'
    export const test = functions.https.onRequest((req, res) => {
        const foo = fs.readFileSync('./foo', 'utf-8')
        console.log(foo)
        res.send(foo)
    })
    

    【讨论】:

    • 那么问题肯定出在其他地方。我发誓我已经在各种路径中尝试过readFileSync,但我总是遇到同样的错误。即使.js.hbs 文件在同一个文件夹中,fs.readFileSync('./template.hbs', 'utf-8') 也会返回错误。
    • 我对那行代码在一个非常简单的函数中没有任何问题。
    • 这解决了它fs.readFileSync(path.join(__dirname,'template.hbs'), 'utf-8');。这两个文件都在同一个文件夹中......去看看。
    • 至于您的编辑,我的 readFileSync 不在函数本身中,而是在 .js 文件的顶部以及其余的要求。不确定这是否有什么不同。
    【解决方案2】:

    解决方案是使用path.join(__dirname,'template.hbs')

    const fs = require('fs');
    const path = require('path');
    const template = fs.readFileSync(path.join(__dirname,'template.hbs'), 'utf-8');
    

    正如@doug-stevenson 指出的,所有文件都包含在最终包中,但由于某种原因,使用相对路径不起作用。使用__dirname 强制使用绝对路径就可以了。

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2019-04-07
      • 2015-12-03
      • 2015-10-04
      • 1970-01-01
      相关资源
      最近更新 更多