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

Headshota picture Headshota · Dec 28, 2011 · Viewed 35.9k times · Source

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?

Answer

ksloan picture ksloan · Feb 10, 2016

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