我有一个 http 云函数,它返回一些动态 HTML。我想使用 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 依赖项的正确方法是什么?
最佳答案
Firebase CLI 将打包函数文件夹中的所有文件(node_modules 除外),并将整个存档发送到 Cloud Functions。它将通过在构建运行您的函数的 docker 镜像时运行 npm install
来重新构建 node_modules。
如果您的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)
})
关于node.js - 如何在 Firebase Cloud Functions 中捆绑和要求非 JS 依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60347291/