Skip to content

Commit

Permalink
Adds stopPort to api
Browse files Browse the repository at this point in the history
Fixes #61
  • Loading branch information
Prithvirajbilla committed Jul 23, 2018
1 parent 24b302d commit 31bfe9f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
4 changes: 4 additions & 0 deletions lib/portfinder.d.ts
Expand Up @@ -15,6 +15,10 @@ interface PortFinderOptions{
* Minimum port (takes precedence over `basePort`).
*/
port?: number;
/**
* Maximum port
*/
stopPort?: number;
}

/**
Expand Down
22 changes: 15 additions & 7 deletions lib/portfinder.js
Expand Up @@ -50,7 +50,7 @@ internals.testPort = function(options, callback) {

options.server.removeListener('listening', onListen);

if (err.code !== 'EADDRINUSE' && err.code !== 'EACCES') {
if (!(err.code == 'EADDRINUSE' || err.code == 'EACCES')) {
return callback(err);
}

Expand Down Expand Up @@ -90,6 +90,9 @@ exports.getPort = function (options, callback) {
options = {};
}

// Largest port number is an unsigned short 2**16 -1=65335
options.stopPort = Number(options.stopPort) || 65535

if (options.host) {

var hasUserGivenHost;
Expand Down Expand Up @@ -137,11 +140,11 @@ exports.getPort = function (options, callback) {
// hosts, without showing them a good error.
var msg = 'Provided host ' + options.host + ' could NOT be bound. Please provide a different host address or hostname';
return callback(Error(msg));
} else {
var idx = exports._defaultHosts.indexOf(currentHost);
exports._defaultHosts.splice(idx, 1);
return exports.getPort(options, callback);
}

var idx = exports._defaultHosts.indexOf(currentHost);
exports._defaultHosts.splice(idx, 1);
return exports.getPort(options, callback);
} else {
// error is not accounted for, file ticket, handle special case
return callback(err);
Expand All @@ -157,7 +160,13 @@ exports.getPort = function (options, callback) {

if (openPorts[0] === openPorts[openPorts.length-1]) {
// if first === last, we found an open port
return callback(null, openPorts[0]);
if(openPorts[0] < option.stopPort) {
return callback(null, openPorts[0]);
}
else {
var msg = 'No open ports found in between '+ options.basePort + ' and ' + options.stopPort;
return callback(Error(msg));
}
} else {
// otherwise, try again, using sorted port, aka, highest open for >= 1 host
return exports.getPort({ port: openPorts.pop(), host: options.host }, callback);
Expand Down Expand Up @@ -329,7 +338,6 @@ exports.nextSocket = function (socketPath) {
match = name.match(/^([a-zA-z]+)(\d*)$/i),
index = parseInt(match[2]),
base = match[1];

if (isNaN(index)) {
index = 0;
}
Expand Down

0 comments on commit 31bfe9f

Please sign in to comment.