How can I add live-reload to my nodejs server

Viewed 60571

This is how can i run my server nodejs. I need to live reload my server when i make changes to the code in the front-end dev

"start": "node server.js"
8 Answers

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.

You can livereload both front and backend changes to the browser with 'livereload', 'connect-livereload', and 'nodemon' packages. This way you don't need Gulp. Here's how the packages team up:

  • livereload opens a high port and notifies the browser of changed public files
  • connect-livereload monkey patches every served HTML page with a snippet that connects to this high port
  • nodemon restarts server on changed backend files

Set up livereload in Express

Set up Express to both start livereload server watching the public directory and ping the browser during nodemon-induced restart:

const livereload = require("livereload");
const connectLivereload = require("connect-livereload");

// open livereload high port and start to watch public directory for changes
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, 'public'));

// ping browser on Express boot, once browser has reconnected and handshaken
liveReloadServer.server.once("connection", () => {
  setTimeout(() => {
    liveReloadServer.refresh("/");
  }, 100);
});

const app = express();

// monkey patch every served HTML so they know of changes
app.use(connectLivereload());

Start Express with nodemon

Start the server with nodemon, for example, with a dedicated watch script npm run watch.

The key point here is to ignore the public directory that's already being watched by livereload. You can also configure files with non-default extensions, like pug and mustache, to be watched.

"scripts": {
  "start": "node ./bin/www",
  "watch": "nodemon --ext js,pug --ignore public"
},

You can read a longer explanation in "Refresh front and backend changes to browser with Express, LiveReload and Nodemon."

Use the npm package called livereload.

Use it in conjunction with nodemon so both client side and server side work flawlessly.

npm install livereload nodemon --save

--save-dev. I know, I know!

Add browser extension. Available for Safari, Firefox, and Google Chrome. Get them here.

Make sure to have this scripts inside package.json.

  "scripts": {
"start": "nodemon server.js && livereload"

}

server.js is my entry point.

Inside the server.js add the following:

const livereload = require('livereload');
const reload = livereload.createServer();
reload.watch(__dirname + "/server.js");

server.js is the file I want livereload to watch. You can add any directory instead of a file as well.

reload.watch(__dirname + "/public");

In terminal: npm start

Click on the extension icon in the browser to connect.

You can also use livereload and nodemon separately in different terminals.

"scripts": {
    "start": "nodemon server.js",
    "livereload": "livereload"
  }

npm start

npm livereload

npm livereload -p PORT_NUMBER if default is port is already used.

Update: sometimes it doesn't work on saving once. A couple more of Ctrl+S reloads again and makes the changes. I don't know if this is a browser caching issue or package issue.

If grunt is used, there is a npm package grunt-contrib-watch for live reloading.

Check out another one called grunt-express-server that can work together.

Related