diff --git a/.gitignore b/.gitignore index 6c2ce5d982..2943e2df00 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .sass-cache .DS_Store .start.pid +.port.tmp public govuk_modules node_modules/* diff --git a/lib/utils.js b/lib/utils.js index d2f19c3b70..b0771490dd 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,6 +1,8 @@ var basicAuth = require('basic-auth'), - prompt = require('prompt'), - portScanner = require('portscanner'); + config = require(__dirname + '/../app/config.js'), + fs = require('fs'); + portScanner = require('portscanner'), + prompt = require('prompt'); /** * Simple basic auth middleware for use with Express 4.x. @@ -35,17 +37,26 @@ exports.basicAuth = function(username, password) { exports.findAvailablePort = function(app){ - var port = (process.env.PORT || 3000); + var port = null; + + try { + port = Number(fs.readFileSync(__dirname+'/../.port.tmp')); + } catch (e){ + port = (process.env.PORT || config.port); + } console.log(''); + // Check that default port is free, else offer to change portScanner.findAPortNotInUse(port, port+50, '127.0.0.1', function(error, availablePort) { if (port == availablePort){ + app.listen(port); console.log('Listening on port ' + port + ' url: http://localhost:' + port); - } - else { + + } else { + // Default port in use - offer to change to available port console.error("ERROR: Port " + port + " in use - you may have another prototype running.\n"); // Set up prompt settings @@ -63,17 +74,21 @@ exports.findAvailablePort = function(app){ pattern: /y(es)?|no?/i, message: 'Please enter y or n' }], function (err, result) { + if (result.answer.match(/y(es)?/i) ) { // User answers yes port = availablePort; + fs.writeFileSync(__dirname+'/../.port.tmp', port); app.listen(port); console.log('Changed to port ' + port + ' url: http://localhost:' + port); - } - else { + + } else { + // User answers no - exit console.log('\nYou can set a new default port in server.js, or by running the server with PORT=XXXX'); console.log("\nExit by pressing 'ctrl + c'"); process.exit(0); + } }); } diff --git a/start.js b/start.js index 76175a706b..d91ad66283 100644 --- a/start.js +++ b/start.js @@ -1,16 +1,29 @@ // Check for `node_modules` folder and warn if missing var fs = require('fs'); + if (!fs.existsSync(__dirname + '/node_modules')) { console.error('ERROR: Node module folder missing. Try running `npm install`'); process.exit(0); } +// remove .port.tmp if it exists +try { + fs.unlinkSync(__dirname + '/.port.tmp'); +} catch(e){} + var gruntfile = __dirname + '/Gruntfile.js'; + require(__dirname + '/node_modules/grunt/lib/grunt.js').cli({ 'gruntfile' : gruntfile }); process.on('SIGINT', function() { - process.kill(process.pid, 'SIGTERM'); - process.exit(); + + // remove .port.tmp if it exists + try { + fs.unlinkSync(__dirname + '/.port.tmp'); + } catch(e){} + + process.exit(0); + });