diff --git a/lib/modules/webserver/index.js b/lib/modules/webserver/index.js index cfd5d7baf..a0b948502 100644 --- a/lib/modules/webserver/index.js +++ b/lib/modules/webserver/index.js @@ -17,20 +17,36 @@ class WebServer { this.port = options.port || this.webServerConfig.port; this.events.emit("status", __("Starting Server")); + this.server = new Server({host: this.host, port: this.port}); + this.testPort(() => { + this.listenToCommands(); + this.registerConsoleCommands(); + this.server.start((_err, message, port) => { + this.logger.info(message); + this.port = port; + this.setServiceCheck(); + }); + }); + } - this.setServiceCheck(); - this.listenToCommands(); - this.registerConsoleCommands(); - - let self = this; - this.server.start((_err, message) => self.logger.info(message)); + testPort(done) { + utils.pingEndpoint(this.host, this.port, 'http', 'http', '', (err) => { + if (err) { // Port is ok + return done(); + } + this.logger.warn(__('Webserver already running on port %s. Assigning an available port', this.port)); + this.port = 0; + this.server.port = 0; + done(); + }); } setServiceCheck() { - let url = 'http://' + canonicalHost(this.host) + ':' + this.port; + const self = this; this.events.request("services:register", 'Webserver', function (cb) { + let url = 'http://' + canonicalHost(self.host) + ':' + self.port; utils.checkIsAvailable(url, function (available) { let devServer = __('Webserver') + ' (' + url + ')'; let serverStatus = (available ? 'on' : 'off'); diff --git a/lib/modules/webserver/server.js b/lib/modules/webserver/server.js index 40356be6b..340f5307c 100644 --- a/lib/modules/webserver/server.js +++ b/lib/modules/webserver/server.js @@ -24,12 +24,14 @@ class Server { serve(req, res, finalhandler(req, res)); }).withShutdown(); - let message = __("webserver available at") + - " " + - ("http://" + canonicalHost(this.hostname) + - ":" + this.port).bold.underline.green; - this.server.listen(this.port, this.hostname); - callback(null, message); + + this.server.listen(this.port, this.hostname, () => { + this.port = this.server.address().port; + callback(null, __("webserver available at") + + " " + + ("http://" + canonicalHost(this.hostname) + + ":" + this.port).bold.underline.green, this.port); + }); } stop(callback) {