How do I render an EJS template file in Node.js?

I'm using Node.js and trying to render an EJS template file. I figured out how to render strings:

    var http = require('http');
    var ejs = require('ejs');

    var server = http.createServer(function(req, res){
        res.end(ejs.render('Hello World'));
    });

    server.listen(3000);

How can I render an EJS template file?


There is a function in EJS to render files, you can just do:

    ejs.renderFile(__dirname + '/template.ejs', function(err, data) {
        console.log(err || data);
    });

Source: Official EJS documentation


var templateString = null;
var fs = require('fs');
var templateString = fs.readFileSync('template.ejs', 'utf-8');

and then you do your thing:

var server = http.createServer(function(req, res){
    res.end(ejs.render(templateString));
});