BrowserSync / browser-sync

Keep multiple browsers & devices in sync when building websites. https://browsersync.io
https://discord.gg/2d2xUThp
Apache License 2.0
12.17k stars 754 forks source link

BrowserSync init before node server is ready #1596

Open ranlix opened 6 years ago

ranlix commented 6 years ago

Issue details

I setup a project with express, gulp-nodemon, browser-sync, when I start the server with gulp command, browsersync inits before node server is ready, the new browser tab keeps blank.

Please specify which version of Browsersync, node and npm you're running

Affected platforms

Browsersync use-case

for all other use-cases, (gulp, grunt etc), please show us exactly how you're using Browsersync

Here is the content of gulpfile.js:

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

gulp.task("node", function(cb) {
  var called = false;
  return nodemon({
    script: './bin/www',
    ext: 'js html njk',
    env: {
      'NODE_ENV': 'development'
    }
  }).on('start', function () {
    console.log('nodemon started');
    if (!called) {
            called = true;
            cb();
        }
  }).on('crash', function () {
    console.log('script crashed for some reason');
  });
});

gulp.task('server', ["node"], function(e) {
  var files = [
    'views/**/*.*',
    'public/**/*.*'
  ];

  browserSync.init(files, {
    proxy: 'http://localhost:3000',
    notify: true,
    port: 3300
  }, function() {
    console.log("browser refreshed.");
  });

  gulp.watch(files).on("change", reload);
});
gulp server
[17:07:19] Using gulpfile ~/projects/liran/expresshome/gulpfile.js
[17:07:19] Starting 'node'...
nodemon started
[17:07:20] Finished 'node' after 183 ms
[17:07:20] Starting 'server'...
[17:07:20] [nodemon] 1.18.3
[17:07:20] [nodemon] to restart at any time, enter `rs`
[17:07:20] [nodemon] watching: *.*
[17:07:20] [nodemon] starting `node ./bin/www`
[Browsersync] Proxying: http://localhost:3000
[Browsersync] Access URLs:
 -----------------------------------
       Local: http://localhost:3300
    External: http://10.0.4.125:3300
 -----------------------------------
          UI: http://localhost:3001
 UI External: http://10.0.4.125:3001
 -----------------------------------
[Browsersync] Watching files...
browser refreshed.
aj-dev commented 6 years ago

You're returning a stream in your "node" gulp task so "server" task doesn't wait for nodemon to start and the callback is ignored. Remove return statement and it should work.

From gulp docs:

Gulp tasks are asynchronous and Gulp uses async-done to wait for the task's completion. Tasks are called with a callback parameter to call to signal completion. Alternatively, Task can return a stream, a promise, a child process or a RxJS observable to signal the end of the task.

https://github.com/gulpjs/gulp/blob/master/docs/API.md#fn