Gulp-Connect-Php + browserSync + Gulp-Connect addr

2019-09-14 14:06发布

问题:

I need an ability to use browserSync with php support and some specific url rewrites. I came up with browserSync with Gulp-Connect-Php packages plus Gulp-Connect + modrewrite. Here is my config:

var  
browserSync  = require('browser-sync'),  
phpconnect   = require('gulp-connect-php'),
connect      = require('gulp-connect'),
modrewrite   = require('connect-modrewrite'),

phpconnect.server({base:'dist/',port: 8010}, function (){
  connect.server({
    port: 8001,
    middleware: function() {
        return [
            modrewrite([
                '^/admin/(.*) - [L]',
                '^([^.]*|.*?\.php)$ http://localhost:8010$1 [P,NC]'
            ])
        ];
    }
 })

 browserSync({
   injectChanges: true,
   proxy: '127.0.0.1:8010'
 });

})

This works fine and exactly as I need. The following problem occurs from time to time when I launch it:

[error] You tried to start Browsersync twice! To create multiple instances, use browserSync.create().init()
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::8001

In other words, browserSync starts BEFORE gulp-connect and utilises port 8010 which should be used by gulp-connect and gulp-connect fails to start.

I installed npm sleep package and added the following line before launching browserSync:

sleep.sleep(15)

in other words, I added a 15 seconds delay before launching browserSync. It works but I bet there is a more elegant solution.

Please, advise.

回答1:

gulp-connect internally wraps connect, which starts a Node http server.

It emits an event once the server starts called listening. https://nodejs.org/api/net.html#net_event_listening

    var  
    browserSync  = require('browser-sync'),  
    phpconnect   = require('gulp-connect-php'),
    connect      = require('gulp-connect'),
    modrewrite   = require('connect-modrewrite'),

    phpconnect.server({base:'dist/',port: 8010}, function (){
      var app = connect.server({
        port: 8001,
        middleware: function() {
            return [
                modrewrite([
                    '^/admin/(.*) - [L]',
                    '^([^.]*|.*?\.php)$ http://localhost:8010$1 [P,NC]'
                ])
            ];
        }
     })
     app.server.on('listening', function () {
       browserSync({
         injectChanges: true,
         proxy: '127.0.0.1:8010'
       });
     });