Created
November 19, 2014 04:54
-
-
Save RyanCopley/66db766f19501bf69a22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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