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);
});
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'));
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.
}
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;
}
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With