getPort = function (options, callback) { if (!callback) { callback = options; options = {}; } if (options.host) { var hasUserGivenHost; for (var i = 0; i < exports._defaultHosts.length; i++) { if (exports._defaultHosts[i] === options.host) { hasUserGivenHost = true; break; } } if (!hasUserGivenHost) { exports._defaultHosts.push(options.host); } } var openPorts = [], currentHost; return async.eachSeries(exports._defaultHosts, function(host, next) { debugGetPort("in eachSeries() iteration callback: host is", host); return internals.testPort({ host: host, port: options.port }, function(err, port) { if (err) { debugGetPort("in eachSeries() iteration callback testPort() callback", "with an err:", err.code); currentHost = host; return next(err); } else { debugGetPort("in eachSeries() iteration callback testPort() callback", "with a success for port", port); openPorts.push(port); return next(); } }); }, function(err) { if (err) { debugGetPort("in eachSeries() result callback: err is", err); // If we get EADDRNOTAVAIL it means the host is not bindable, so remove it // from exports._defaultHosts and start over. For ubuntu, we use EINVAL for the same if (err.code === 'EADDRNOTAVAIL' || err.code === 'EINVAL') { if (options.host === currentHost) { // if bad address matches host given by user, tell them // // NOTE: We may need to one day handle `my-non-existent-host.local` if users // report frustration with passing in hostnames that DONT map to bindable // 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)); } 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); } } // sort so we can compare first host to last host openPorts.sort(function(a, b) { return a - b; }); debugGetPort("in eachSeries() result callback: openPorts is", openPorts); if (openPorts[0] === openPorts[openPorts.length-1]) { // if first === last, we found an open port return callback(null, openPorts[0]); } else { // otherwise, try again, using sorted port, aka, highest open for >= 1 host return exports.getPort({ port: openPorts.pop(), host: options.host }, callback); } }); }
...
## Usage
The `portfinder` module has a simple interface:
``` js
var portfinder = require('portfinder');
portfinder.getPort(function (err, port) {
//
// `port` is guaranteed to be a free port
// in this scope.
//
});
```
...
getPortPromise = function (options) { if (typeof Promise !== 'function') { throw Error('Native promise support is not available in this version of node.' + 'Please install a polyfill and assign Promise to global.Promise before calling this method'); } if (!options) { options = {}; } return new Promise(function(resolve, reject) { exports.getPort(options, function(err, port) { if (err) { return reject(err); } resolve(port); }); }); }
...
```
Or with promise (if Promise are supported) :
``` js
const portfinder = require('portfinder');
portfinder.getPortPromise()
.then((port) => {
//
// `port` is guaranteed to be a free port
// in this scope.
//
})
.catch((err) => {
...
getPorts = function (count, options, callback) { if (!callback) { callback = options; options = {}; } var lastPort = null; async.timesSeries(count, function(index, asyncCallback) { if (lastPort) { options.port = exports.nextPort(lastPort); } exports.getPort(options, function (err, port) { if (err) { asyncCallback(err); } else { lastPort = port; asyncCallback(null, port); } }); }, callback); }
n/a
getSocket = function (options, callback) { if (!callback) { callback = options; options = {}; } options.mod = options.mod || parseInt(755, 8); options.path = options.path || exports.basePath + '.sock'; // // Tests the specified socket // function testSocket () { fs.stat(options.path, function (err) { // // If file we're checking doesn't exist (thus, stating it emits ENOENT), // we should be OK with listening on this socket. // if (err) { if (err.code == 'ENOENT') { callback(null, options.path); } else { callback(err); } } else { // // This file exists, so it isn't possible to listen on it. Lets try // next socket. // options.path = exports.nextSocket(options.path); exports.getSocket(options, callback); } }); } // // Create the target `dir` then test connection // against the socket. // function createAndTestSocket (dir) { mkdirp(dir, options.mod, function (err) { if (err) { return callback(err); } options.exists = true; testSocket(); }); } // // Check if the parent directory of the target // socket path exists. If it does, test connection // against the socket. Otherwise, create the directory // then test connection. // function checkAndTestSocket () { var dir = path.dirname(options.path); fs.stat(dir, function (err, stats) { if (err || !stats.isDirectory()) { return createAndTestSocket(dir); } options.exists = true; testSocket(); }); } // // If it has been explicitly stated that the // target `options.path` already exists, then // simply test the socket. // return options.exists ? testSocket() : checkAndTestSocket(); }
...
}
else {
//
// This file exists, so it isn't possible to listen on it. Lets try
// next socket.
//
options.path = exports.nextSocket(options.path);
exports.getSocket(options, callback);
}
});
}
//
// Create the target `dir` then test connection
// against the socket.
...
nextPort = function (port) { return port + 1; }
...
options.server.removeListener('listening', onListen);
if (err.code !== 'EADDRINUSE' && err.code !== 'EACCES') {
return callback(err);
}
internals.testPort({
port: exports.nextPort(options.port),
host: options.host,
server: options.server
}, callback);
}
options.server.once('error', onError);
options.server.once('listening', onListen);
...
nextSocket = function (socketPath) { var dir = path.dirname(socketPath), name = path.basename(socketPath, '.sock'), match = name.match(/^([a-zA-z]+)(\d*)$/i), index = parseInt(match[2]), base = match[1]; if (isNaN(index)) { index = 0; } index += 1; return path.join(dir, base + index + '.sock'); }
...
}
}
else {
//
// This file exists, so it isn't possible to listen on it. Lets try
// next socket.
//
options.path = exports.nextSocket(options.path);
exports.getSocket(options, callback);
}
});
}
//
// Create the target `dir` then test connection
...
getPort = function (options, callback) { if (!callback) { callback = options; options = {}; } if (options.host) { var hasUserGivenHost; for (var i = 0; i < exports._defaultHosts.length; i++) { if (exports._defaultHosts[i] === options.host) { hasUserGivenHost = true; break; } } if (!hasUserGivenHost) { exports._defaultHosts.push(options.host); } } var openPorts = [], currentHost; return async.eachSeries(exports._defaultHosts, function(host, next) { debugGetPort("in eachSeries() iteration callback: host is", host); return internals.testPort({ host: host, port: options.port }, function(err, port) { if (err) { debugGetPort("in eachSeries() iteration callback testPort() callback", "with an err:", err.code); currentHost = host; return next(err); } else { debugGetPort("in eachSeries() iteration callback testPort() callback", "with a success for port", port); openPorts.push(port); return next(); } }); }, function(err) { if (err) { debugGetPort("in eachSeries() result callback: err is", err); // If we get EADDRNOTAVAIL it means the host is not bindable, so remove it // from exports._defaultHosts and start over. For ubuntu, we use EINVAL for the same if (err.code === 'EADDRNOTAVAIL' || err.code === 'EINVAL') { if (options.host === currentHost) { // if bad address matches host given by user, tell them // // NOTE: We may need to one day handle `my-non-existent-host.local` if users // report frustration with passing in hostnames that DONT map to bindable // 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)); } 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); } } // sort so we can compare first host to last host openPorts.sort(function(a, b) { return a - b; }); debugGetPort("in eachSeries() result callback: openPorts is", openPorts); if (openPorts[0] === openPorts[openPorts.length-1]) { // if first === last, we found an open port return callback(null, openPorts[0]); } else { // otherwise, try again, using sorted port, aka, highest open for >= 1 host return exports.getPort({ port: openPorts.pop(), host: options.host }, callback); } }); }
...
## Usage
The `portfinder` module has a simple interface:
``` js
var portfinder = require('portfinder');
portfinder.getPort(function (err, port) {
//
// `port` is guaranteed to be a free port
// in this scope.
//
});
```
...
getPortPromise = function (options) { if (typeof Promise !== 'function') { throw Error('Native promise support is not available in this version of node.' + 'Please install a polyfill and assign Promise to global.Promise before calling this method'); } if (!options) { options = {}; } return new Promise(function(resolve, reject) { exports.getPort(options, function(err, port) { if (err) { return reject(err); } resolve(port); }); }); }
...
```
Or with promise (if Promise are supported) :
``` js
const portfinder = require('portfinder');
portfinder.getPortPromise()
.then((port) => {
//
// `port` is guaranteed to be a free port
// in this scope.
//
})
.catch((err) => {
...
getPorts = function (count, options, callback) { if (!callback) { callback = options; options = {}; } var lastPort = null; async.timesSeries(count, function(index, asyncCallback) { if (lastPort) { options.port = exports.nextPort(lastPort); } exports.getPort(options, function (err, port) { if (err) { asyncCallback(err); } else { lastPort = port; asyncCallback(null, port); } }); }, callback); }
n/a
getSocket = function (options, callback) { if (!callback) { callback = options; options = {}; } options.mod = options.mod || parseInt(755, 8); options.path = options.path || exports.basePath + '.sock'; // // Tests the specified socket // function testSocket () { fs.stat(options.path, function (err) { // // If file we're checking doesn't exist (thus, stating it emits ENOENT), // we should be OK with listening on this socket. // if (err) { if (err.code == 'ENOENT') { callback(null, options.path); } else { callback(err); } } else { // // This file exists, so it isn't possible to listen on it. Lets try // next socket. // options.path = exports.nextSocket(options.path); exports.getSocket(options, callback); } }); } // // Create the target `dir` then test connection // against the socket. // function createAndTestSocket (dir) { mkdirp(dir, options.mod, function (err) { if (err) { return callback(err); } options.exists = true; testSocket(); }); } // // Check if the parent directory of the target // socket path exists. If it does, test connection // against the socket. Otherwise, create the directory // then test connection. // function checkAndTestSocket () { var dir = path.dirname(options.path); fs.stat(dir, function (err, stats) { if (err || !stats.isDirectory()) { return createAndTestSocket(dir); } options.exists = true; testSocket(); }); } // // If it has been explicitly stated that the // target `options.path` already exists, then // simply test the socket. // return options.exists ? testSocket() : checkAndTestSocket(); }
...
}
else {
//
// This file exists, so it isn't possible to listen on it. Lets try
// next socket.
//
options.path = exports.nextSocket(options.path);
exports.getSocket(options, callback);
}
});
}
//
// Create the target `dir` then test connection
// against the socket.
...
nextPort = function (port) { return port + 1; }
...
options.server.removeListener('listening', onListen);
if (err.code !== 'EADDRINUSE' && err.code !== 'EACCES') {
return callback(err);
}
internals.testPort({
port: exports.nextPort(options.port),
host: options.host,
server: options.server
}, callback);
}
options.server.once('error', onError);
options.server.once('listening', onListen);
...
nextSocket = function (socketPath) { var dir = path.dirname(socketPath), name = path.basename(socketPath, '.sock'), match = name.match(/^([a-zA-z]+)(\d*)$/i), index = parseInt(match[2]), base = match[1]; if (isNaN(index)) { index = 0; } index += 1; return path.join(dir, base + index + '.sock'); }
...
}
}
else {
//
// This file exists, so it isn't possible to listen on it. Lets try
// next socket.
//
options.path = exports.nextSocket(options.path);
exports.getSocket(options, callback);
}
});
}
//
// Create the target `dir` then test connection
...