Q:

creating dynamic servers in Gulp using connect

Is it possible to check if a server port is taken before creating it in Gulp?
I'm doing this right now:
/**
 * Start LiveReload Server
 */
gulp.task('connect', function() {

    var connect = require('connect'),
        app = connect()
        .use(require('connect-livereload')({ port: liveReloadPort }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'));

    require('http').createServer(app)
        .listen(serverPort)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:' + serverPort);
        });
});

gulp.task('serve', ['connect', 'styles'], function() {
    require('opn')('http://localhost:' + serverPort);
});

I'd like to be able to have the server port be dynamic and check if that port is already in use. Is this possible?

A:

Thanks to @IlanFrumer I found a solution by using this.
Implemented like this:
var serverPort;

/**
 * Start LiveReload Server
 */
gulp.task('connect', function () {

    var portfinder = require('portfinder'),
        connect = require('connect'),
        app = connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'));

    portfinder.getPort(function (err, port) { 

        serverPort = port;

        require('http').createServer(app)
            .listen(port)
            .on('listening', function () {
                console.log('Started connect web server on http://localhost:' + port);
            });
    });
});

gulp.task('serve', ['connect', 'styles'], function () {
    require('opn')('http://localhost:' + serverPort);
});

there are other factors taking place in the functions above, but the meat of it is there. Thanks again @IlanFrumer!

