oss-specs/specs

View on GitHub
bin/www

Summary

Maintainability
Test Coverage
#!/usr/bin/env node

/**
 * Module dependencies.
 */

 // Only require newrelic if we've provided API KEY
if(process.env.NEW_RELIC_LICENSE_KEY) {
  console.log("Setting up new relic monitoring");
  require('newrelic');
}

var app = require('../app');
var http = require('http');
var cp = require('child_process');

var appName = require('../package.json').name || 'myLovelyApp';

/**
 * Set a process name so we can kill this later.
 */
process.title = appName;

/**
 * Get port from environment and store in Express.
 */
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.on('error', onError);
server.on('listening', onListening);
server.listen(port);

/**
 * 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.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  var exit = false;
  var errorMessage = 'Error: ';
  switch (error.code) {
    case 'EACCES':
      errorMessage += bind + ' requires elevated privileges.';
      exit = true;
      break;
    case 'EADDRINUSE':
      errorMessage += bind + ' is already in use.';
      exit = true;
      break;
    default:
      errorMessage += error.message || 'Something broke.';

    console.error(errorMessage);

    // If the process is a child process (e.g. started in Gulp)
    // then inform the parent process that the server has errored.
    if (process.send) {
      process.send(startMessage);
    }

    // Exit or rethrow.
    if (exit) {
      process.exit(1);
    } else {
      throw error;
    }
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  var startMessage = 'Server listening on ' + bind;
  console.log(startMessage);

  // If the process is a child process (e.g. started in Gulp)
  // then inform the parent process that the server has started.
  if (process.send) {
    process.send(startMessage);
  }
}