Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write file from a template in Node.js

I want to generate a file from a template. For example, I have a handlebars (but it can be another template) like this

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

Then, I make a query to the database, and return the view to the browser. But now, I dont want return the view, but save it as a file on the server disk. How can I do it?

I try generate and save from the browser, but I want do the proccess in the server

like image 497
Giancarlo Ventura Avatar asked Oct 10 '16 16:10

Giancarlo Ventura


1 Answers

You have to "compile" the template manually and write the result into the respective file. Like:

const fs = require('fs');
const Handlebars = require('handlebars');

const source = '<div>{{title}}</div>';
const template = Handlebars.compile(source);

const contents = template({title: 'Wohooo!'});

fs.writeFile('contents.html', contents, err => {
    if (err) {
        return console.error(`Autsch! Failed to store template: ${err.message}.`);
    }

    console.log(`Saved template!');
});
like image 151
notion Avatar answered Oct 03 '22 22:10

notion