【问题标题】:Rendering EJS template throws an error this.templateText.replace is not a function渲染 EJS 模板抛出错误 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);

【问题讨论】:

    标签: javascript node.js ejs


    【解决方案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);
    猜你喜欢
    • 2023-01-15
    • 1970-01-01
    • 2017-11-27
    • 2015-05-01
    • 2017-04-01
    • 2023-02-07
    • 2010-10-30
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多