Auto-starting Node.js application on Vagrant when

2019-02-11 03:44发布

问题:

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?

回答1:

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


回答2:

Ates' answer provides quite a bit of bloat in my opinion (pm2, Gulp, gulp-shell and an excessive gulpfile?!). A great alternative to nodemon is a similar lib called node-dev. It's also mentioned under nodemon's issues with Vagrant (which you skimmed through, I imagine).

Basic usage:

node-dev --no-deps app.js

All the best :)



回答3:

nodemon works very good for me:

Install

sudo npm install -g nodemon
npm install --save-dev nodemon

Run

nodemon -L app.js