最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Write file from a template in Node.js - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Oct 10, 2016 at 16:39 Giancarlo VenturaGiancarlo Ventura 8572 gold badges11 silver badges27 bronze badges 3
  • fs.writeFile? – Bergi Commented Oct 10, 2016 at 17:00
  • @Bergi I know how to write a file, but not how to write it from a template – Giancarlo Ventura Commented Oct 10, 2016 at 17:34
  • You don't write if from a template. You write a node program that reads in a template, fetches the data, does the substitutions (using any template engine you like), and writes the result. – Bergi Commented Oct 10, 2016 at 17:35
Add a comment  | 

1 Answer 1

Reset to default 20

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!');
});
发布评论

评论列表(0)

  1. 暂无评论