node.js - 如何在 Firebase Cloud Functions 中捆绑和要求非 JS 依赖项?
问题描述
我有一个返回一些动态 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 没有将此文件与其余文件捆绑在一起。
根据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 Cloud Function 中包含和要求非 JS 依赖项的正确方法是什么?
解决方案
Firebase CLI 将打包您的函数文件夹中的所有文件,除了 node_modules,并将整个存档发送到 Cloud Functions。它将通过npm install
在构建运行您的函数的 docker 映像时运行来重构 node_modules。
如果您的 something.hbs 位于您的函数文件夹下的 /templates 中,您应该能够./templates/something.hbs
从顶级 index.js 中引用它。如果您的 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)
})
推荐阅读
- java - 如何更新在java中监听按钮的组件
- javascript - 未兑现承诺的决议
- google-sheets - 如何在A列中搜索所有文本匹配的列并将B列中的所有对应值相加 Excel
- sql - SQL - 删除重复行而不保留原始行
- back4app - 带有java的Android工作室
- pine-script - 根据其他输入选择显示/隐藏输入字段
- python - Face_Recognition 加载编码文件时出现问题
- asp.net-core - AWS Lambda 与 Kestrel .NET Core 性能对比
- python - 将文件从芹菜任务发送到烧瓶路线
- javascript - Javascript - 如何返回数组中最大的四个数字?