javascript - 渲染 EJS 模板报错 this.templateText.replace is not a function

标签 javascript node.js ejs

我正在尝试从文件中呈现 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);

最佳答案

事实证明,fs.readFile 在回调 data 中返回一个原始缓冲区,而 ejs.redner 需要一个字符串。

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

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

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

关于javascript - 渲染 EJS 模板报错 this.templateText.replace is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123428/

相关文章:

javascript - Primefaces 中的客户端验证

node.js - Node JS 中不使用 process.stdout.write 输出日志的方法?

layout - 在 Express/EJS 中,如何更改默认布局?

javascript - 使用express js获取404渲染 View ejs

javascript - 从 <input> 获取 id= 和 value= 的动态值,并将它们设为变量以在 javascript 中使用它们

javascript - window.print() 在 chrome 中工作但在 safari 中不起作用

javascript - 如何让我的机器人扮演一个角色并将其交给我?

android - 在哪里存储构建 Artifact : Grunt, node.js 后端、github、android、iOS 客户端

javascript - 如何为 React 创建 npm 包

node.js - 如何在 ejs/express 中的全局变量中使用函数?