Grunt Task for Serving Static HTML Files

– 06/30/13

Sometimes you need to serve up some static HTML, Javascript, CSS, and other static assets in your grunt project.

Part of my Qunit test suite in a recent project required making AJAX requests for Javascript templates. I needed a way to serve the HTML files in my test directory – I couldn’t simply view the file in the browser because the browser doesn’t allow AJAX requests over the file:// scheme.

Here’s how you can fire up an HTTP server for you grunt projects.

Writing & running the task

First off, install the shelljs module.

npm install shelljs --save-dev

Note, the –save-dev flag adds the dependency to your package.json file, making your life easier in the future.

Then add this task to Gruntfile.js:

grunt.registerTask('serve', 'Serves any directory on given port', function (env) {
  var shell = require('shelljs');
  var port  = grunt.option('port') || 8000;
  var dir   = grunt.option('dir')  || '.';
  console.log(['Serving', dir,'on port:', port].join(' '))
  shell.exec('cd '+ dir +' && python -m SimpleHTTPServer ' + port);

Then start up the server with the following command:

grunt serve

In my case, I run the command like so, serving the test directory on port 5000:

grunt serve --port=5000 --dir=test