GruntJS

GruntJS is a JavaScript task runner. It can be used to automate various tasks for your application with minimum effort which increases the developer's productivity.

GruntJS includes plugins for various tasks. For example, nodemon plugin automatically restarts the node server whenever any JavaScript file changes in your application. So, you don't have to stop and restart the node server manually everytime you modify JavaScript. The grunt-contrib-cssmin plugin can be used to compress CSS files. The grunt-jsfmt plugin can be used to format, search or rewrite the JavaScript in your application.

Visit gruntjs.com/plugins listing to know about all the available plugins in GruntJS.

GruntJS Installation

In order to use GruntJS, you first need to install Grunt's command line interface (CLI) globally using following npm command.

C:\> npm install -g grunt-cli

Gruntfile.js

The Gruntfile.js or Gruntfile.coffee is the main file where you need to configure all the tasks for your application which you want to automate using different plugins.

Let's see how to use grunt-nodemon plugin to run node monitor of your Node.js server.

Nodemon

The grunt-nodemon is a monitor for Node.js server. It restarts the node server immediately if any JavaScript file changes in your Node.js application.

First of all, install the nodemon plugin into your application using following command.

C:\ProjectFolder> npm install grunt nodemon --save-dev

Now, create Gruntfile.js file into the root folder of your application and write the following JavaScript.

Gruntfile.js

module.exports = function (grunt) {
    grunt.initConfig({
    
        nodemon: {
            dev: {
                script: 'server.js'
               
            }
        }
    });
    
    grunt.loadNpmTasks('grunt-nodemon');
    grunt.registerTask('default', ['nodemon'])
};
 

In the above example, we have specified nodemon task in the grunt.initConfig() method for restarting the Node.js server whenever any JavaScript file changes in your project. At the end, loadNpmTasks() method loads the specified plugin which is grunt-nodemon in this case. The registerTask() method registers the default task to run whenever gruntjs starts.

Now, open command prompt and navigate to your project folder and write command:grunt. This will start monitoring your project as shown below.

run nodemon gruntjs
Run GruntJS

Now, whenever you change any of your JS files it will restart the web server as shown below.

run gruntjs
Restarting Node Server

This is how you can use various GruntJS plugins for the Node.js application.

Visit getting-started guide to learn more about GruntJS and configuring-tasks guide to know how to configure different tasks.

Want to check how much you know Node.js?