From 62b9b779012ae7fc8f56af377a2560d179d532dc Mon Sep 17 00:00:00 2001 From: ZauberNerd Date: Thu, 29 Mar 2018 13:23:25 +0200 Subject: [PATCH] feat(express): choose next free port when hops-config.port is falsy This commit enables hops-express to choose the next free port when no port is set via hops-config. --- packages/express/lib/utils.js | 45 +++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/packages/express/lib/utils.js b/packages/express/lib/utils.js index d9344d8c6..37c74efdf 100644 --- a/packages/express/lib/utils.js +++ b/packages/express/lib/utils.js @@ -2,6 +2,7 @@ var fs = require('fs'); var url = require('url'); +var net = require('net'); var path = require('path'); var http = require('http'); var https = require('https'); @@ -19,17 +20,38 @@ function getStatsFromFile() { return stats || {}; } -function defaultCallback(error) { +function getPort(host, port, max) { + return new Promise(function(resolve, reject) { + max = max || Math.min(65535, port + 50); + if (port > max) { + return reject(new Error('unable to find free port')); + } + var server = net.createServer(); + server.on('error', function() { + resolve(getPort(host, port + 1, max)); + server.close(); + }); + server.listen(port, host, function() { + server.once('close', function() { + resolve(port); + }); + server.close(); + }); + }); +} + +function defaultCallback(error, server) { if (error) { - console.error(error.stack.toString()); + console.error(error.stack ? error.stack.toString() : error.toString()); } else { + var address = server.address(); console.log( 'hops: Server listening at ' + url.format({ protocol: hopsConfig.https ? 'https' : 'http', hostname: - hopsConfig.host === '0.0.0.0' ? 'localhost' : hopsConfig.host, - port: hopsConfig.port, + address.address === '0.0.0.0' ? 'localhost' : address.address, + port: address.port, pathname: hopsConfig.basePath, }) ); @@ -53,9 +75,18 @@ exports.run = function run(app, callback) { } else { server = http.createServer(app); } - server.listen(hopsConfig.port, hopsConfig.host, function(error) { - (callback || defaultCallback)(error, server); - }); + function listen(port) { + server.listen(port || hopsConfig.port, hopsConfig.host, function(error) { + (callback || defaultCallback)(error, server); + }); + } + if (hopsConfig.port) { + listen(); + } else { + getPort(hopsConfig.host, 8080) + .then(listen) + .catch(defaultCallback); + } }; exports.rewritePath = function rewritePath(req, res, next) {