Using mustache.js along with node.js?

Problem

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?

Problem courtesy of: Industrial

Solution

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...
});

Solution courtesy of: diff_sky

View additional discussion.