www 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!/usr/bin/env node
  2. 'use strict';
  3. /*
  4. *
  5. * Copyright 2016-2017 Red Hat, Inc, and individual contributors.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. */
  20. /**
  21. * Module dependencies.
  22. */
  23. const logger = require('../logger.js');
  24. const app = require('../app');
  25. const http = require('http');
  26. /**
  27. * Get port from environment and store in Express.
  28. */
  29. const port = normalizePort(process.env.PORT || '8080');
  30. app.set('port', port);
  31. /**
  32. * Create HTTP server.
  33. */
  34. const server = http.createServer(app);
  35. /**
  36. * Listen on provided port, on all network interfaces.
  37. */
  38. server.listen(port);
  39. server.on('error', onError);
  40. server.on('listening', onListening);
  41. /**
  42. * Normalize a port into a number, string, or false.
  43. */
  44. function normalizePort (val) {
  45. const port = parseInt(val, 10);
  46. if (isNaN(port)) {
  47. // named pipe
  48. return val;
  49. }
  50. if (port >= 0) {
  51. // port number
  52. return port;
  53. }
  54. return false;
  55. }
  56. /**
  57. * Event listener for HTTP server "error" event.
  58. */
  59. function onError (error) {
  60. if (error.syscall !== 'listen') {
  61. throw error;
  62. }
  63. const bind = typeof port === 'string'
  64. ? 'Pipe ' + port
  65. : 'Port ' + port;
  66. // handle specific listen errors with friendly messages
  67. switch (error.code) {
  68. case 'EACCES':
  69. logger.error(bind + ' requires elevated privileges');
  70. process.exit(1);
  71. case 'EADDRINUSE':
  72. logger.error(bind + ' is already in use');
  73. process.exit(1);
  74. default:
  75. throw error;
  76. }
  77. }
  78. /**
  79. * Event listener for HTTP server "listening" event.
  80. */
  81. function onListening () {
  82. const addr = server.address();
  83. const bind = typeof addr === 'string'
  84. ? 'pipe ' + addr
  85. : 'port ' + addr.port;
  86. logger.info('Listening on ' + bind);
  87. }