Giancarlo Ventura Granados Giancarlo Ventura Granados - 10 months ago 57
Javascript Question

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">
<div class="body">

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

Answer Source

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!');