在异步 fs.readFile 的回调中使用 EJS 呈现 HTML 模板?

Rendering HTML template with EJS in a callback for asynchronous fs.readFile?

我使用 fs.readFileSync 轻松完成了此操作,但我想异步执行此操作。我的代码如下。

    function send(err, str){

        if(err){
            console.log(err);
        }

        var template = ejs.render(str, 'utf8', {name: data.name});

        transporter.sendMail({
            from: myEmail,
            to: anotherEmail,
            subject: mySubject,
            html: template,
            attachments: images
        }, function(err, response) {
            if(err){
                console.log(err);
            }
        });
    }

    fs.readFile('emailTemplate.ejs', send);

所以我为 fs.readFile 进行了自己的回调,以便在读取文件后呈现电子邮件,放入正确的名称,然后使用 nodemailer 将其发送出去。然而,它不喜欢这样。如果没有问题,它会得到错误,但在尝试呈现模板时渲染会抛出以下错误。

TypeError: Object (Followed by the entire HTML of the template) has no method 'indexOf' at Object.exports.parse (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:144:21) at exports.compile (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:229:15) at Object.exports.render (/home/ubuntu/workspace/node_modules/ejs/lib/ejs.js:289:10) at send (/home/ubuntu/workspace/routes/email.js:171:28) at fs.readFile (fs.js:272:14) at Object.oncomplete (fs.js:108:15)

虽然同步执行它工作正常。

    var str = fs.readFileSync('emailTemplate.ejs', 'utf8');

    var template = ejs.render(str, {
        name: data.name
    });

谁能告诉我为什么会这样?

尝试设置 fs.readFile 调用的编码,例如:

fs.readFile('emailTemplate.ejs', 'utf8', send);

异步调用 readFile 时没有默认编码,而是 returns 原始缓冲区。目前,此缓冲区正在发送到 EJS render 调用并失败。

有关详细信息,请参阅 node documentation for readFile

fs.readFilefs.readFileSyncdocumentation表示

If no encoding is specified, then the raw buffer is returned.

因为您提供同步版本的编码,但不提供异步版本,它们的行为不同。

如果你试试这个:

fs.readFile('emailTemplate.ejs', {encoding: "utf8"}, send);

应该可以。