渲染EJS模板会抛出一个错误this.templateText.replace不是一个函数

我想从文件呈现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); 

事实certificate, fs.readFile在callbackdata返回一个原始缓冲区,而ejs.redner期望一个string。

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

如果你想从fs.readFile得到一个string,那么你需要传递编码作为第二个参数:

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