gulp.js livereload with express server?

Timmerz picture Timmerz · May 15, 2014 · Viewed 28.6k times · Source

I am trying to setup my gulpfile.js to use livereload on an express server without much luck. I see examples out there but they seem to be related to a static file server.

http://code.tutsplus.com/tutorials/gulp-as-a-development-web-server--cms-20903 http://rhumaric.com/2014/01/livereload-magic-gulp-style/

So I have an app.js file which does the standard express server with jade files, etc. What I want to do is get it to work with livereload from a gulp.js boot.

app.set('port', process.env.PORT || 3000);
    var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});

There are lots of plugins like gulp-livereload, connect-livereload, gulp-connect, gulp-watch so how can I get this wired up?

Answer

Amit Portnoy picture Amit Portnoy · Jun 18, 2014

I've added code that

  1. Detects changes in server files and reloads the server via nodemon

  2. Waits for a couple seconds after process reload in order to give the server time to run its initialization code.

  3. Triggers a change in a livereload server

note 1 : Your build should also include a livereload server and attach livereload scripts to html files before calling the 'serve' task

note 2: This is an asynchronous task that never ends, do not use it as a dependency of other tasks


gulp.task('serve', function (cb) {
    nodemon({
        script  : <server start file>,
        watch   : <server files>
        //...add nodeArgs: ['--debug=5858'] to debug 
        //..or nodeArgs: ['--debug-brk=5858'] to debug at server start
    }).on('start', function () {
        setTimeout(function () {
            livereload.changed();
        }, 2000); // wait for the server to finish loading before restarting the browsers
    });
});