Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering EJS template throws an error this.templateText.replace is not a function

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);
like image 722
Lukasz Wiktor Avatar asked Jul 15 '17 22:07

Lukasz Wiktor


1 Answers

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
});
like image 170
Lukasz Wiktor Avatar answered Oct 20 '22 00:10

Lukasz Wiktor