How can I add live-reload to my nodejs server How can I add live-reload to my nodejs server express express

How can I add live-reload to my nodejs server


first:

npm install -g nodemon

next add a script line to your package.json

"live": "nodemon server.js" 

now when you npm live it'll live reload

for more details see https://github.com/remy/nodemon

update if live page reload is also needed

npm install -g livereloadlivereload . -w 1000 -d

for more details see https://github.com/napcs/node-livereload


Restarting server is one thing, refreshing browser is another thing. For server watching I use nodemon. Nodemon can see when changes occur in any types of files. But nodemon cannot refresh browser page. For this I use browser sync.

I use both in gulp.

So, dependencies from package.json to make it work:

"devDependencies": {"browser-sync": "^2.24.5","gulp": "^3.9.1","gulp-nodemon": "^2.2.1"}

In server file (my server is in ./bin/www, yours can be in server.js, app.js or elsewhere), express server listens to port 3001.

var port = normalizePort(process.env.PORT || '3001');var server = http.createServer(app);server.listen(port);

Next thing is to run nodemon and browser sync in gulp.Full contents of gulpfile.js

var gulp = require('gulp');var nodemon = require('gulp-nodemon');var browserSync = require('browser-sync').create();gulp.task('gulp_nodemon', function() {  nodemon({    script: './bin/www', //this is where my express server is    ext: 'js html css', //nodemon watches *.js, *.html and *.css files    env: { 'NODE_ENV': 'development' }  });});gulp.task('sync', function() {  browserSync.init({    port: 3002, //this can be any port, it will show our app    proxy: 'http://localhost:3001/', //this is the port where express server works    ui: { port: 3003 }, //UI, can be any port    reloadDelay: 1000 //Important, otherwise syncing will not work  });  gulp.watch(['./**/*.js', './**/*.html', './**/*.css']).on("change", browserSync.reload);});gulp.task('default', ['gulp_nodemon', 'sync']);

When running gulp in terminal, it will start watching server as well as refreshing browser on change in any files.

Although we specify port 3001 in express server, our app will be working on port 3002, as we write in browser-sync. 3001 will be used as proxy.


npm install browser-refresh -g

and add your main js

 if (process.send) {     process.send('online'); }

for example

app.listen(port, function() {    console.log('Listening on port %d', port);    if (process.send) {        process.send('online');    }});

and add your index page before body close tag.

<script src="{process.env.BROWSER_REFRESH_URL}"></script>

and start your server on termial instead node server.js

browser-refresh server.js