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
1 Answer
Reset to default 24It 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
});