Skip to content Skip to sidebar Skip to footer

Node.js - Auto Refresh In Dev

I am trying to improve the DEV experience in my Node. To do that, I want to: a) restart my server when server-side code is changed b) refresh the browser when client-side code is

Solution 1:

You actually don't need to use gulp for this to work.

a) restart my server when server-side code is changed

Install nodemon globally using npm i -g nodemon then on your app folder do nodemon or nodemon ${index-file-of-your-app}.

b) refresh the browser when client-side code is changes.

Use browserify or webpack. I prefer using webpack; you may need to learn about the configuration a little bit but the good thing with webpack is that you don't need to refresh it. Once changes are found the changes will be reflected on the browser automatically. https://github.com/webpack/docs/wiki/hot-module-replacement-with-webpack

Solution 2:

You can livereload both front and backend changes to the browser by using the 'livereload', 'connect-livereload', and 'nodemon' packages together. Also, this way you don't need Gulp or Grunt. Here's how the packages play together:

  • 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 is then used to restart the server on changed backend files

Set up livereload in Express

Set up the 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 changesconst 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

Then you'd start the server with nodemon, for example, with a dedicated watch script by running 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."

Solution 3:

@mateeyow is right.

But if you want the browser to reload automaticaly, you also need livereload-plugin.

Enable webpack-hot-replacement only replace code in browser's memory, livereload-plugin do reload it.

See rock for example: https://github.com/orange727/rock/blob/master/app/templates/webpack/webpack.make.js#L255

Just as:

webpackConfig.plugins: [
  new webpack.HotModuleReplacementPlugin(),
  new LiveReloadPlugin({
    appendScriptTag: true,
    port: config.ports.livereload,
})];

Solution 4:

I might be missing some context (e.g. I'm not sure what input represents), however, I think the npm module reload might solve your problem. Here's an example from the npm package page:

var express = require('express')
  , http = require('http')
  , path = require('path')
  , reload = require('reload')
  , bodyParser = require('body-parser')
  , logger = require('morgan')

var app = express()

var publicDir = path.join(__dirname, '')

app.set('port', process.env.PORT || 3000)
app.use(logger('dev'))
app.use(bodyParser.json()) //parses json, multi-part (file), url-encoded  

app.get('/', function(req, res) {
  res.sendFile(path.join(publicDir, 'index.html'))
})

var server = http.createServer(app)

//reload code here //optional reload delay and wait argument can be given to reload, refer to [API](https://github.com/jprichardson/reload#api) below 
reload(server, app, [reloadDelay], [wait])

server.listen(app.get('port'), function(){
  console.log("Web server listening on port " + app.get('port'));
});

Solution 5:

The EADDRINUSE error is normally due to a connection already open on the specified port. This is probably due to a previous instance of the connection not being correctly closed when restarting the app.

Take a look at this gist and in particular try something like this in your gulp file:

'use strict';

var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');

gulp.task('default', ['browser-sync'], function () {});

gulp.task('browser-sync', ['nodemon'], function() {
    browserSync.init(null, {
        proxy: "http://localhost:3002"
    });
});

gulp.task('nodemon', function (cb) {

    var started = false;

    returnnodemon({
        script: 'app.js'
    }).on('start', function () {
        // to avoid nodemon being started multiple timesif (!started) {
            cb();
            started = true; 
        } 
    });
});

Post a Comment for "Node.js - Auto Refresh In Dev"