www 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env node
  2. /**
  3. * Module dependencies.
  4. */
  5. var app = require('../app');
  6. var debug = require('debug')('express-test:server');
  7. var http = require('http');
  8. /**
  9. * Get port from environment and store in Express.
  10. */
  11. var port = normalizePort(process.env.PORT || '3000');
  12. app.set('port', port);
  13. /**
  14. * Create HTTP server.
  15. */
  16. var server = http.createServer(app);
  17. /**
  18. * Listen on provided port, on all network interfaces.
  19. */
  20. server.listen(port);
  21. server.on('error', onError);
  22. server.on('listening', onListening);
  23. /**
  24. * Normalize a port into a number, string, or false.
  25. */
  26. function normalizePort(val) {
  27. var port = parseInt(val, 10);
  28. if (isNaN(port)) {
  29. // named pipe
  30. return val;
  31. }
  32. if (port >= 0) {
  33. // port number
  34. return port;
  35. }
  36. return false;
  37. }
  38. /**
  39. * Event listener for HTTP server "error" event.
  40. */
  41. function onError(error) {
  42. if (error.syscall !== 'listen') {
  43. throw error;
  44. }
  45. var bind = typeof port === 'string'
  46. ? 'Pipe ' + port
  47. : 'Port ' + port;
  48. // handle specific listen errors with friendly messages
  49. switch (error.code) {
  50. case 'EACCES':
  51. console.error(bind + ' requires elevated privileges');
  52. process.exit(1);
  53. break;
  54. case 'EADDRINUSE':
  55. console.error(bind + ' is already in use');
  56. process.exit(1);
  57. break;
  58. default:
  59. throw error;
  60. }
  61. }
  62. /**
  63. * Event listener for HTTP server "listening" event.
  64. */
  65. function onListening() {
  66. var addr = server.address();
  67. var bind = typeof addr === 'string'
  68. ? 'pipe ' + addr
  69. : 'port ' + addr.port;
  70. debug('Listening on ' + bind);
  71. }