最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Rendering EJS template throws an error this.templateText.replace is not a function - Stack Overflow

programmeradmin3浏览0评论

I'm trying to render an EJS template from file but I'm getting an error 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);

I'm trying to render an EJS template from file but I'm getting an error 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);
Share Improve this question asked Jul 15, 2017 at 22:49 Lukasz WiktorLukasz Wiktor 20.4k6 gold badges71 silver badges83 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 24

It turns out that fs.readFile returns a raw buffer in callback data while ejs.redner is expecting a string.

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

If you want to get a string from fs.readFile then you need to pass encoding as a second argument:

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

评论列表(0)

  1. 暂无评论