【问题标题】:Firebase Functions Typescript - Sending Emails with html templatesFirebase Functions Typescript - 使用 html 模板发送电子邮件
【发布时间】:2018-12-02 14:48:33
【问题描述】:

我正在尝试使用 fs.readFile('../emailTemplates/template.html') 从 index.ts 读取 html 文件

我的文件夹:

--src
  --index.ts
  --UsersFunctions
    --UserFunctions.ts
  --emailTemplates
    --template.html

来自 index.ts :

import * as UsersFunctions from './UsersFunctions/UsersFunctions';
export const newUserRegister = UsersFunctions.onCreateNewUser;

来自 UsersFunctions.ts

 export const onCreateNewUser = functions.firestore.document('users/allUsers/usersData/{userId}').onCreate(async (snap, context) => {
  fs.readFile("../emailTemplates/template.html", {encoding: 'utf-8'}, (err, html) => {
    if (err) {
        console.log(err);

    }
    else {

    }
  });       
 }

我从 firebase 函数中得到一个错误:

Error: ENOENT: no such file or directory, open '../emailTemplates/template.html'
at Error (native)
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'user_code/lib/emailTemplates/newUserRegisterHtmlTemplate.html'

我只想发送一封带有 html 模板的电子邮件 也许还有另一种方法可以做到这一点? 我厌倦了搜索,但没有找到关于带有打字稿的 frirebase 功能的电子邮件模板

【问题讨论】:

    标签: typescript firebase google-cloud-functions fs


    【解决方案1】:

    问题是您的模板路径与您的项目文件组织不匹配。我建议你只把 TypeScript 源代码放在src 中,其他所有你想读写的文件都放在你的functions 文件夹下,和src 同级。因此,您可以像这样组织文件:

    /functions
        /src
            /index.ts
            /other source files
        /emailTemplates
            /template.html
    

    然后,在 index.ts 中,您可以使用相同的路径 ../emailTemplates/template.html 读取 template.html。

    【讨论】:

    • 您能否编辑您的问题以显示演示问题的整个最小函数(不仅仅是一行)?
    • 读取模板的代码文件实际上在树中比 src 更深。也许您需要在相对路径前面再添加一个 .. 才能在树中更进一步。
    • 也试过 ../../emailTemplates 没有运气,只是想读取一个文件,为什么这么难......顺便说一句,当我使用只有 javascript 而没有 typescript 的 firebase 函数时,一切都很好
    • @EranAbir 我遇到了同样的问题。尝试使用 nunjucks 渲染 HTML 模板,但它不起作用。
    • 您是否将您的模板复制到 lib/ 文件夹中?这使它对我有用
    【解决方案2】:

    您需要使用Path.join(__dirname, ...) 才能从磁盘读取文件。 Firebase Functions 会正确上传代码周围的其他文件;但是 Functions 的内部结构会导致 process.CWD 信息混淆相对导入。

    const templatePath = Path.join(__dirname, 'emailTemplates', 'template.html');
    fs.readFile(templatePath, 'utf-8', (err, template) => {
        // ...
    });
    

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2017-11-10
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多