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