Node.js – Running node app from grunt with watch

gruntjsnode.js

So, I have the grunt file below. I'm wanting to add a task that will start my node app and watch for changes in a directory and restart. I have been using supervisor, node-dev (which are great) but I want to run one command and start my whole app. There has got to be a simple way to do this, but I'm just missing it. It is written in coffeescript as well (not sure if that changes things)…

module.exports = function(grunt) {
  grunt.initConfig({
    /*exec: {
        startApi: {
            command: "npm run-script start-api"
        }
    },*/
    //static server
    server: {
        port: 3333,
        base: './public',
        keepalive: true
    },

    // Coffee to JS compilation
    coffee: {
        compile: {
            files: {
                './public/js/*.js': './src/client/app/**/*.coffee'
            },
            options: {
                //basePath: 'app/scripts'
            }
        }
    },


    mochaTest: {
        all: ['test/**/*.*']
    },


    watch: {
        coffee: {
            files: './src/client/app/**/*.coffee',
            tasks: 'coffee'
        },
        mochaTest: {
            files: 'test/**/*.*',
            tasks: 'mochaTest'
        }
    }
});

grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-mocha-test');
//grunt.loadNpmTasks('grunt-exec');

grunt.registerTask( 'default', 'server coffee mochaTest watch' );
};

As you can see in the comments, I tries grunt-exec, but the node command stops the execution of the other tasks.

Best Answer

You can set grunt to run default task and the watch task when you start your node app:

in app.js

var cp = require('child_process');
var grunt = cp.spawn('grunt', ['--force', 'default', 'watch'])

grunt.stdout.on('data', function(data) {
    // relay output to console
    console.log("%s", data)
});

Then just run node app as normal!

Credit

Related Topic