Server-side Mustache templating with Node.js

November 17, 2014

Node.js and Mustache make it simple to write a Web application using server-side templating to generate HTML.

First, install Mustache:

$ npm install mustache

Next, whip up a view template, using Mustache to fill in the holes:


This implies a model containing a couple of fields, title and messages:

var model = {
    title: 'Mustache'
  , messages: [
        'Mustache is a handy templating language.'
      , 'It goes well with JavaScript.'
      , 'It also goes well with Node.js.'
      , 'It even goes well with Scala!'
      , 'Here it\'s used to generate server-side HTML.'

We'll need a way to read the template and generate the view:

var mustache = require('mustache')

function render(write) {
  return function (err, buf) {
    var template = buf.toString('utf8')
    var html = mustache.to_html(template, model)

All that's left is to wrap it up in an HTTP server:

var http     = require('http')
var fs       = require('fs')

var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'})
  function respond(html) {
  fs.readFile('template.mustache', render(respond))