Using mustache.js along with node.js?

Industrial picture Industrial · Dec 18, 2011 · Viewed 8.1k times · Source

After becoming fond with mustache.js template-style, I would like continue using it in node.js.

I've been able to install it and confirm that it's working, but I just can't get my head around how to use it to template files.

How do I load a template called template.html and apply mustache's magic to it within node.js?

Answer

diff_sky picture diff_sky · Feb 25, 2012

fs.readFileSync is the synchronous version of fs.readFile, so it will be blocking. Here's a basic example of how you could use fs.readFile with mustache.js which would return the mustache template in the callback.

var object_to_render = {key: "value", ...};

fs.readFile(path_to_mustache_template, function (err, data) {
  if (err) throw err;
  var output = Mustache.render(data.toString(), object_to_render);

  // do something with output... 
});