diff --git a/templates/js/www b/templates/js/www index 2622a321..46a99f6f 100755 --- a/templates/js/www +++ b/templates/js/www @@ -12,7 +12,7 @@ var http = require('http'); * Get port from environment and store in Express. */ -var port = process.env.PORT || '3000'; +var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** @@ -29,6 +29,26 @@ server.listen(port); server.on('error', onError); server.on('listening', onListening); +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + /** * Event listener for HTTP server "error" event. */ @@ -38,14 +58,18 @@ function onError(error) { throw error; } + var bind = typeof port === 'string' + ? 'Pipe ' + port + : 'Port ' + port + // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': - console.error('Port ' + port + ' requires elevated privileges'); + console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': - console.error('Port ' + port + ' is already in use'); + console.error(bind + ' is already in use'); process.exit(1); break; default: