From bc20a064972c014757b0d3f3435e1440bad066b9 Mon Sep 17 00:00:00 2001 From: billchurch Date: Fri, 20 May 2016 10:50:46 -0400 Subject: [PATCH] Increment port feature If the specified port is being used, added a feature that it would increment the port by 1 and try again, logging the chosen port to the console. removed console.log of config --- index.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/index.js b/index.js index d7c8cef..3a4439c 100644 --- a/index.js +++ b/index.js @@ -11,6 +11,20 @@ var readConfig = require('read-config'), console.log(config); +var isPortTaken = function(port, fn) { + var net = require('net') + var tester = net.createServer() + .once('error', function (err) { + if (err.code != 'EADDRINUSE') return fn(err) + fn(null, true) + }) + .once('listening', function() { + tester.once('close', function() { fn(null, false) }) + .close() + }) + .listen(port) +} + function checkParams(arr) { return function(req, res, next) { // Make sure each param listed in arr is present in req.query @@ -34,6 +48,14 @@ function checkParams(arr) { server.listen({ host: config.listen.ip, port: config.listen.port +}).on('error', function (err) { + if (err.code === 'EADDRINUSE') { + config.listen.port++; + console.log('Address in use, retrying on port ' + config.listen.port); + setTimeout(function () { + server.listen(config.listen.port); + }, 250); + } }); app.use(express.static(__dirname + '/public')).use(term.middleware()).use(function(req, res, next) {