渲染 EJS 模板抛出错误 this.templateText.replace is not a function

Posted

技术标签:

【中文标题】渲染 EJS 模板抛出错误 this.templateText.replace is not a function【英文标题】:Rendering EJS template throws an error this.templateText.replace is not a function 【发布时间】:2017-12-20 18:18:11 【问题描述】:

我正在尝试从文件中呈现 EJS 模板,但我收到错误 this.templateText.replace is not a function

const http = require('http');
const fs = require('fs');
const ejs = require('ejs');

const server = http.createServer(function(req, res)
    fs.readFile('index.ejs', function(err, data) 
        if (err) 
            res.end("Error");
        

        res.end(ejs.render(data,  title: "Hello" ));
    );
);

server.listen(4000);

【问题讨论】:

【参考方案1】:

原来fs.readFile 在回调data 中返回一个原始缓冲区,而ejs.redner 期待一个字符串。

如果未指定编码,则返回原始缓冲区。

如果您想从fs.readFile 获取字符串,则需要将编码作为第二个参数传递:

fs.readFile('index.ejs', 'utf-8', function(err, data) 
    // now data is a string
);

【讨论】:

或使用ejs.renderFile(filename, data);

以上是关于渲染 EJS 模板抛出错误 this.templateText.replace is not a function的主要内容,如果未能解决你的问题,请参考以下文章