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

拈花ヽ惹草 提交于 2019-11-30 16:23:52

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

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 :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!