Live Reloading in Express

Posted on Sat 31 October 2015 in JavaScript

Gaffa tape time. Getting iteration times down is important when building software, if nothing else it makes it more fun and help you keep the flow going. With this in mind, let's get live reloading working with Mustache templates on an express-based local development server.

Let's start simple by serving some templates:

import express from 'express';
import mustache from 'mustache';
import fs from 'fs';

// Create a new express server instance.
const app = express();

// Handle GET requests to `/hello`.
app.get('/hello', (req, res) => {
  // Read the template and JSON data from the local filesystem.
  const tpl = fs.readFileSync('./hello.mustache', 'utf8');
  const data = JSON.parse(fs.readFileSync('./hello.json'));

  // Serve back the rendered template.
  res.send(mustache.render(tpl, data));
});

console.log(`server started at http://localhost:3000`);
app.listen(3000);

So far so good, but let's make it live-reload so we can do this:

https://gyazo.com/326ca72b98bce37af177d9e8d5143279

First stop is to grab the livereload module from NPM; this creates its own server which serves a javascript file used for relaying changes back to the browser; it also sets up a file-system monitor to detect changes when you modify your source files.

// Create a livereload server
const reloadServer = livereload.createServer({
  // Reload on changes to these file extensions.
  exts: [ 'json', 'mustache' ],
  // Print debug info
  debug: true
});

// Specify the folder to watch for file-changes.
reloadServer.watch(__dirname);

The last piece is to inject the livereload.js into your HTML; the connect-livereload module takes care of this; just drop it into your app before your define your routes:

// Inject the livereload.js script tag into pages.
app.use(livereloadMiddleware());

Et viola, live reloading of mustache templates and their associated data. Full source over on github.