Automatic first available port selection applied to gulp livereload on node.js
Hello all,
During work I needed to take in consideration multiple instances of gulp w/ livereload.
Normally Gulp starts livereload on port 35729 and doesn’t auto-select the first available automatically.
This case can also be applied to any Node.js script that requires finding the first available port.
First produce a function that takes 3 arguments: the starting port, an optional ending port and a callback.
var net = require('net');
function getAvailablePort(start, end, cb) {
if (!cb) {
if (!end) {
cb = start;
start = 8000;
end = 60000;
} else {
cb = end;
end = 60000;
}
}
if (start >= end) {
return cb(new Error('No available ports to launch livereload.'));
}
var c = net.connect(start, function() {
c.destroy();
getAvailablePort(start + 1, end, cb);
});
c.on('error', function() {
cb(null, start);
});
}
The script will keep calling itself until it finds a free port between the starting port and the ending port. To check the availability of a port it simply create a connection instance and kill it afterwards.
Applied to gulp the result can be the following:
gulpfile.js
gulp.task('connect', function() {
getAvailablePort(35729, function(err, availableLiveReloadPort) {
connect.server({
livereload: {
port: availableLiveReloadPort
}
});
});
});
This way, before assigning the default livereload port, we will search the first free port starting from 35729.
Neat and minimal!
No comments yet.