Search code examples
node.jsvagrantnodemon

Auto-starting Node.js application on Vagrant when there are changes to code


I'm running a Node.js application on a Vagrant box and want the Node.js application to restart when anything changes on the host machine.

But I couldn't use nodemon. It doesn't pick up the changes in time. When I use the -L flag, it consumes too much CPU on the guest machine. These are currently well-known issues.

I've also tried Vagrant's rsync-auto, but it wasn't responsive enough for some reason.

Is there a workaround? Perhaps something I can apply on the host machine?


Solution

  • There seem to be other tools you can try on the guest machine as alternatives to nodemon, but watching for file changes will be the fastest on the host machine.

    Here's a workaround that has worked for me:

    This gist: Use a watcher on the host machine and issue an SSH command to the guest machine to restart the application.

    Here's a recipe (you can use any other tools you like):

    First, grab pm2:

    npm install -g pm2
    

    And launch your Node.js application via pm2:

    pm2 app/server.js
    

    Then grab Gulp:

    npm install -g gulp-cli
    npm install --save-dev gulp
    

    And gulp-shell:

    npm install --save-dev gulp-shell
    

    Then create a gulpfile.js:

    var gulp = require('gulp');
    var shell = require('gulp-shell');
    
    gulp.task('server:watch', function () {
      gulp.watch('app/**/*.js', [ 'server:restart' ]);
    });
    
    gulp.task('server:restart', shell.task([ 'vagrant ssh -- pm2 restart server' ]));
    

    You're done. To start watching the files and automatically start the server on file changes:

    gulp server:watch