From cfe571ec8b60f5df7af039ff65dd5bcd2cad5707 Mon Sep 17 00:00:00 2001 From: Joe Lanman Date: Thu, 18 Feb 2016 19:04:41 +0000 Subject: [PATCH] fix port restart issue #148 --- lib/utils.js | 27 +++++++++++++++++++++------ start.js | 13 +++++++++++-- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/lib/utils.js b/lib/utils.js index d2f19c3b70..0b1d3b055d 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,6 +1,7 @@ var basicAuth = require('basic-auth'), prompt = require('prompt'), - portScanner = require('portscanner'); + portScanner = require('portscanner'), + fs = require('fs'); /** * Simple basic auth middleware for use with Express 4.x. @@ -35,17 +36,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 || 3000); + } 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 +73,22 @@ 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..06a16dbac9 100644 --- a/start.js +++ b/start.js @@ -1,16 +1,25 @@ // 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); } 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.kill(process.pid, 'SIGTERM'); + process.exit(0); + });