Monday, March 10, 2014

Use GruntJS to LiveReload browser and restart server

A quick guide to show on how to setup GruntJS to restart your NodeJS server everytime there’s a file changed in your project.

1. Install GruntJs and task Modules

Back to TOC
To use GruntJS you should have NodeJs (>0.8.0) installed.

You can use GruntJS for multiple projects, therefore we will install grunt command line interface globally on the machine.

npm install -g grunt-cli

We will also need a package.json file.

npm init

Next we will need the following node modules.
The option --save-dev will save the modules as development dependencies in package.json file.

npm install grunt --save-dev
npm install load-grunt-tasks --save-dev
npm install grunt-contrib-watch --save-dev
npm install grunt-express-server --save-dev

2. Configure Gruntfile.js

Back to TOC
Create a new gruntjs configuration file

touch gruntfile.js

The basic content of gruntfile.js is basically one big “wrapper” function to be exported.

The basic format of this function.
1. Load plugin(s)
2. Project configuration
3. Register Task(s)

//gruntfile.js
module.exports = function(grunt){

  // [TODO]: Load plugin(s)
  // [TODO]: Project configuration
  // [TODO]: Register Task(s)
  grunt.registerTask('default',[]);
};

Load plugin(s)

Back to TOC
Add this line to load the plugin(s) that already installed in you node modules.

...
  //Load plugin(s)
  require('load-grunt-tasks')(grunt);
...

Project Configuration

Back to TOC
We will use grunt-express-server and grunt-contrib-watch here.

  • Setup the express server task for starting the server.

  • Configure watch task to watch for any *.js file changes and rerun the express task to start server.

...
  //Project Configuration
  grunt.initConfig({
    express: {
      dev: {
        options :{
          script: './app.js'
        }
      }
    },
    watch: {
      express: {
        files: ['**/*.js'],   //Files to be watched
        tasks: ['express:dev'],   //(Re)start the server
        options: {            //Server options
          spawn: false       //Must have for reload
        }
      }
    }
  });

...

Register Task(s)

Back to TOC
Finally we will register the task to initiate the server and watcher.

...
  //Register Task
  grunt.registerTask('default',['express:dev','watch']);
...

Save the work.


3. Test Application

Back to TOC
Let’s create app.js for testing purpose.

//app.js
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World\n');
}).listen(3000);

console.log('Server running');

Run Grunt Tasks

Back to TOC
To run grunt tasks, simply run the following:

grunt

Now try to change 'Hello World' to 'Watch Me!' in app.js file and save it. You will see that the server has restarted.


4. LiveReload

Back to TOC
Right now we have a server that will reload itself whenever a file changed. Let’s go for the extra miles to let our browser refresh when code changes.

Browser auto refresh or so called “LiveReload” is quite easy to implement.

  • Modify the watch task’s option.
    Add livereload: true to option. Default port is 35729.
    gruntfile.js
    watch: {
      express: {
        files: ['**/*.js'],   
        tasks: ['express:dev'],   
        options: {            
          spawn: false,
          livereload: true  //Enable LiveReload
        }
      }
    }
  • Add this script <script src="http://localhost:35729/livereload.js"></script> into our response.

app.js

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  //For LiveReload
  res.write("<script src=\"http://"+req.headers.host.split(":")[0]+":35729/livereload.js\"></script>");

  res.end('Hello World\n');
}).listen(3000);
console.log('Server running');

That’s it, you do not need to implement any livereload.js.

  • Run your server again using grunt. Now try to change Hello World again to something else and you will see your server has restarted and your browser has refresh itself to show the changes.

There are a lot of LiveReload middleware available for Connect-, Express- based application which you can use it if needed.

Express.js User

Back to TOC
You can add the LiveReload middleware manually like this:

//Custom LiveReload middleware
app.use(function (req,res,next){
  res.body = "<script src=\"http://localhost:35729/livereload.js\"></script>";
  next();
});

//Output to client
app.use(function (req,res){
    res.body += "Hello World\n";
    res.send(res.body);
});

//You will need the second argument here.
//Without it, grunt will not start the watch task but
//you still be able to request the server.
app.listen(3000, function(){console.log("Server is up"});

Download

Back to TOC
You can find the code here.
https://github.com/Zev23/grunt-watch-guide






Copyright © Zev23.com 2014 All Rights Reserved. No part of this website may be reproduced without Zev23.com’s express consent.

No comments: