-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
66 lines (57 loc) · 1.76 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import http from 'http';
import express from 'express';
import logger from "morgan";
import indexRouter from './routes/index.js';
class Server {
app = express();
port = this.#normalizePort(process.env.PORT || '3000');
instance = null;
constructor() {
this.#configureApp();
this.instance = http.createServer(this.app);
this.#configureServer();
}
#configureApp() {
this.app
.set('port', this.port)
.use(logger('dev'))
.use(express.json())
.use('/', indexRouter);
}
#configureServer() {
this.instance
.listen(this.port)
.on('error', this.#onError.bind(this))
.on('listening', this.#onListening.bind(this));
}
#normalizePort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) { return val } // named pipe
if (port >= 0) { return port } // port number
return false;
}
#onListening() {
const addr = this.instance.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + (addr ? addr.port : 'Unknown');
console.log('Listening on ' + bind);
}
#onError(error) {
if (error.syscall !== 'listen') throw error;
const bind = `${typeof this.port === 'string' ? 'Pipe' : 'Port'} ${this.port}`;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
}
new Server();