Skip to content

Instantly share code, notes, and snippets.

@AirBorne04
Created August 19, 2018 13:52
Show Gist options
  • Save AirBorne04/c25f7d289996f336379033511aa403f2 to your computer and use it in GitHub Desktop.
Save AirBorne04/c25f7d289996f336379033511aa403f2 to your computer and use it in GitHub Desktop.
Find a usable port by given port-range
var netstat = require("node-netstat");
var getNextAvailablePort = function (portRangeAsString) {
var portString = portRangeAsString || process.env.USE_PORT_RANGE;
if (portString) {
var portStart, portLast;
portStart = parseInt(portString.split("-")[0]);
portLast = parseInt(portString.split("-")[1]);
var portArr = [];
netstat({
sync: true,
filter: {
local: {
address: null
}
}
}, portArr.push.bind(portArr));
portArr = portArr.map(
portInfo => portInfo.local.port
).filter(
// filter port range and also the index to eliminate duplicates
(portNr, index, arr) => portNr >= portStart && portNr <= portLast && arr.indexOf(portNr) === index
);
if (portArr.length > portLast - portStart) {
throw new Error("No available port in the range " + portString);
}
else {
for(var i = portStart; i <= portLast; ++i) {
if (portArr.indexOf(i) < 0) {
return i;
}
}
}
}
// node will decide whihc port to take
else {
return 0;
}
}
console.log(
getNextAvailablePort()
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment