Reputation:
I'm writing a node server that listens to 2 ports, ports 80 and 8080. It works great if I sudo
it. What I'd like to do is make it run on just port 8080 if it can't connect to port 80 but I don't know how to detect that case. I hoped it would throw when I called server.listen
as in
var ports = [80, 8080];
var servers = [];
var goodPorts = [];
for (var ii = 0; ii < ports.length; ++ii) {
var port = ports[ii];
var server = http.createServer(handleRequests);
try {
server.listen(port);
servers.push(server);
goodPorts.push(port);
} catch (e) {
// not sure how to check for this. Maybe this?
if (e.toString().indexOf("EACCES") < 0) {
throw e;
} else {
console.error("could NOT connect to port: " + port);
}
}
}
console.log("Listening on port(s): " + goodPorts.join(", ") + "\n");
But server.listen
doesn't throw. The exception happens sometime after setup. (in other words, after that console.log
at the bottom.
How can I check if it's going to work at runtime?
Upvotes: 1
Views: 375
Reputation: 14881
server.listen accepts a callback that will receive an error if the port is not usable:
server.listen(80, function (err) {
if (!err)
return;
server.listen(8080, function (err) {
if (err)
throw err;
});
});
Upvotes: 3