Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render EJS template and save it as a file

I have been cracking my head over this, I am trying to render an EJS file and save the result as an HTML, the saving part seems to be working but I can't get the full hand of how to return the data from the 'template' file.

var fileName = 'public/cv/' + userID + '_default.html';
    var stream = fs.createWriteStream(fileName);
    function buildHtml(request) {

        var sveducations = JSON.parse(SQReducations);
        var header = '';

        return '<!DOCTYPE html>'
            + '<html><header>' + header + '</header><body>' +
                html
            +
            '</body></html>';
    };
    stream.once('open', function (fd) {
        var html = buildHtml();
        stream.end(html);
    });
like image 353
Tino Costa 'El Nino' Avatar asked Aug 11 '16 08:08

Tino Costa 'El Nino'


2 Answers

This is the simplest way to save html string rendered from ejs.

var ejs  = require('ejs');
var fs   = require('fs');
var data = {} // put your data here.  

var template = fs.readFileSync('./template.ejs', 'utf-8');
var html     = ejs.render ( template , data );

fs.writeFileSync("./html.html", html, 'utf8');

If you want to read data from JSON file

var data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));

8/12 edit

Use try catch to get error message.

var ejs  = require('ejs');
var fs   = require('fs');
var data = {} // put your data here.  

try {
    var template = fs.readFileSync('./template.ejs', 'utf-8');
    var html     = ejs.render ( template , data );

    fs.writeFileSync("./result.html", html, 'utf8');

}catch (e){
    console.log(e)  // If any error is thrown, you can see the message.
}
like image 150
Radian Jheng Avatar answered Sep 19 '22 04:09

Radian Jheng


Now you don't need anymore to load the template with a readFile() or readFileSync() call. You can simply use ejs.renderFile(pathToTemplate, data, cal) :

const data = {};

ejs.renderFile(path.join(__dirname, '../views/template.ejs'), data, (err, result) => {
    if (err) {
        logger.log('info', 'error encountered: ' + err);
        // throw err;
    }
    else {
        try {
            fs.writeFileSync('./html.html', result, 'utf8');
        } catch(err) {
            if (err) {
                throw err;
            }
        }

    }
});
like image 36
Eliott Avatar answered Sep 19 '22 04:09

Eliott