尝试在我的节点服务器上分离我的 SendGrid html 电子邮件模板

Trying to separate my SendGrid html email templates on my node server

我是 运行 节点服务器,我正在使用 SendGrid 发送电子邮件。我需要将我的电子邮件 HTMLs 与我的 js 文件分开,以便我可以从单个库中修改它们。我现在拥有的是:

const express = require('express')
const config = require('config')
const sgMail = require('@sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
sgMail.setApiKey(sendKey)

  const msg = {
    to: "test@test.com",
    from: "test@test.com",
    subject: 'Welcome To The App',
    text: 'Text is here',
    html: <strong>HTML HERE</strong>
  }

  sgMail.send(msg)

我想在我当前的 js 文件之外调用我的 HTML 属性,而不是在我的 msg 对象中写入 HTML。

我怎样才能有一个单独的 welcomeEmail.html 文件并将其添加到我的 js 文件中的 msg 对象?

我试过 fs 模块,但我只有

Error: ENOENT: no such file or directory, open './welcomeEmail.html'

无论如何我都无法读取我的 HTML 文件。

知道我遗漏了什么吗?

可以使用fs,您可能从错误的路径读取。

使用这个:

fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{//do Something});

确保 welcomeEmail.html 在项目中的正确位置。

请记住 readFileasync 所以你应该在回调中完成你的其余代码,所以你的代码应该是这样的(取决于用例是什么):

const express = require('express')
const config = require('config')
const sgMail = require('@sendgrid/mail')
const sendKey = config.get('SENDGRID_API_KEY')
const fs = require('fs')
sgMail.setApiKey(sendKey)


fs.readFile('./welcomeEmail.html', 'utf8', (err, content)=>{

  if(err){
      console.log(err);
  }
  else{
      let msg = {
        to: "test@test.com",
        from: "test@test.com",
        subject: 'Welcome To The App',
        text: 'Text is here',
        html: content
      }

      sgMail.send(msg)
  }
});