Skip to content

Instantly share code, notes, and snippets.

@RyanCopley
Created November 19, 2014 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanCopley/66db766f19501bf69a22 to your computer and use it in GitHub Desktop.
Save RyanCopley/66db766f19501bf69a22 to your computer and use it in GitHub Desktop.
//Attempt up to 5 ports, so 8000, 8001, 8002, 8003, 8004.
setupHTTPServer(5);
function setupHTTPServer(max, count){
count = (count === undefined) ? 0 : count;
//The 2nd parameter means we only listen to local connections
var server = app.listen(8000+count, "127.0.0.1", function (err) {
if (server.address()){
console.log('Listening on port "+server.address().port);
}
});
//If a EADDRINUSE error gets raised, try the next port. If one of them is successful, we're good to go.
server.on("error", function (err){
server.removeListener("error", function (){}); // Always remove listeners!
if (count < max-1) {
//Attempt again, recursion strategy.
setupHTTPServer(max, count+1);
}else{
//It seems like we already have every port listened to. We don't need this process, so lets exit.
process.exit();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment