Gulp to watch when node app.listen() is invoked or to port (livereload, nodejs and gulp)

纵然是瞬间 提交于 2019-12-22 08:46:42

问题


I am trying to get gulp-livereload to work with my nodejs server. I am using gulp-nodemon to restart the server after changes to the files, this works. I am having trouble invoking livereload.reload() at the correct time.

I am currently invoking livereload.reload() on the .on('start'... in my gulpfile.js (whenever my nodemon starts a script). This works but it takes a few seconds. The reason is when nodemon starts to run the nodejs script it invokes livereload.listen() before the script has invoked app.listen(port), so my browser refreshs without the server being ready.

Is there a way to listen if the nodejs nodemon script has invoked app.listen(port) or perhaps listen to see if a specific port is being used?

I have fixed the issue with a small sleep but it just feels so wrong and dirty.


回答1:


Use readable event to monitor stdout of child process.

example:

nodemon({script: 'app.js',
         nodeArgs: ['--harmony'],
         stdout: false})
    .on('readable', function(data) {
        this.stdout.on('data', function(chunk) {
            if (/koa server listening/.test(chunk)) {
                console.log('livereload');
                livereload.reload();
            }
            process.stdout.write(chunk);
        });
        this.stderr.pipe(process.stderr);
    });

app.js

app.listen(3000, function(err) {
    console.log('koa server listening');
});



回答2:


Here is a an example of simple and tested livereload solution based on connect server and connect-livereload and gulp-livereload plugins if that is of any help:


var gulp = require('gulp');
var connect = require('connect');
var connectLivereload = require('connect-livereload');
var opn = require('opn');
var gulpLivereload = require('gulp-livereload');

var config = {
    rootDir: __dirname,
    servingPort: 8080,

    // the files you want to watch for changes for live reload
    filesToWatch: ['*.{html,css,js}', '!Gulpfile.js']
}

// The default task - called when you run `gulp` from CLI
gulp.task('default', ['watch', 'serve']);

gulp.task('watch', ['connect'], function () {
  gulpLivereload.listen();
  gulp.watch(config.filesToWatch, function(file) {
    gulp.src(file.path)
      .pipe(gulpLivereload());
  });
});

gulp.task('serve', ['connect'], function () {
  return opn('http://localhost:' + config.servingPort);
});

gulp.task('connect', function(){
  return connect()
    .use(connectLivereload())
    .use(connect.static(config.rootDir))
    .listen(config.servingPort);
});



来源:https://stackoverflow.com/questions/29217978/gulp-to-watch-when-node-app-listen-is-invoked-or-to-port-livereload-nodejs-a

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