From bbbe311004aa0b2e61f1678099c02cb9a136d418 Mon Sep 17 00:00:00 2001 From: Kaveh Khorram Date: Tue, 10 Apr 2018 08:48:44 -0700 Subject: [PATCH] Dynamic port switching (#516) --- lib/start-server.js | 51 +++++++++++++++++++++++++++------------------ package.json | 2 +- 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/lib/start-server.js b/lib/start-server.js index 6c90089f22ad..56995630e080 100755 --- a/lib/start-server.js +++ b/lib/start-server.js @@ -37,23 +37,34 @@ const program = require('commander'); program.option('--port ', 'Specify port number').parse(process.argv); -const port = parseInt(program.port, 10) || 3000; - -tcpPortUsed - .check(port, 'localhost') - .then(function(inUse) { - if (inUse) { - console.error(chalk.red('Port ' + port + ' is in use')); - process.exit(1); - } else { - console.log('Starting Docusaurus server on port ' + port + '...'); - // start local server on specified port - const server = require('./server/server.js'); - server(port); - } - }) - .catch(function(ex) { - setTimeout(function() { - throw ex; - }, 0); - }); +var port = process.env.PORT || 3000; +var numAttempts = 0; +var maxAttempts = 10; +checkPort(); + +function checkPort() { + tcpPortUsed + .check(port, 'localhost') + .then(function(inUse) { + if (inUse && numAttempts >= maxAttempts) { + console.log("Reached max attempts, exiting. Please open up some ports or increase the number of attempts and try again.") + process.exit(1) + } else if (inUse) { + console.error(chalk.red('Port ' + port + ' is in use')); + // Try again but with port + 1 + port += 1; + numAttempts += 1; + checkPort(); + } else { + console.log('Starting Docusaurus server on port ' + port + '...'); + // start local server on specified port + const server = require('./server/server.js'); + server(port); + } + }) + .catch(function(ex) { + setTimeout(function() { + throw ex; + }, 0); + }); +} diff --git a/package.json b/package.json index 8bca6ad4b245..2b3dbe347300 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "url": "https://github.com/facebook/Docusaurus.git" }, "scripts": { - "ci-check": "yarn prettier:diff", + "ci-check": "yarn prettier && yarn prettier:diff", "format:source": "prettier --config .prettierrc --write \"lib/**/*.js\"", "format:examples": "prettier --config .prettierrc --write \"examples/**/*.js\"", "nit:source": "prettier --config .prettierrc --list-different \"lib/**/*.js\"",