1 | const debug = require('./debug')('server');
|
2 | const http = require('http');
|
3 |
|
4 | let server;
|
5 | let port;
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const start = function start(app) {
|
18 | const config = require('./config')();
|
19 | port = normalizePort(config.get('port'));
|
20 | server = http.createServer(app);
|
21 |
|
22 | |
23 |
|
24 |
|
25 |
|
26 | app.set('port', port);
|
27 | server.listen(port);
|
28 | server.on('error', onError);
|
29 | server.on('listening', onListening);
|
30 |
|
31 | return server;
|
32 | };
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | const stop = function stop(done) {
|
39 | try {
|
40 | server.close(done);
|
41 | } catch(e) {
|
42 |
|
43 | }
|
44 | };
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 | function normalizePort(val) {
|
56 | const port = parseInt(val, 10);
|
57 |
|
58 | if (isNaN(port)) {
|
59 |
|
60 | return val;
|
61 | }
|
62 |
|
63 | if (port >= 0) {
|
64 |
|
65 | return port;
|
66 | }
|
67 |
|
68 | return false;
|
69 | }
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | function onError(error) {
|
80 | if (error.syscall !== 'listen') {
|
81 | throw error;
|
82 | }
|
83 |
|
84 | const bind = typeof port === 'string'
|
85 | ? `Pipe ${port}`
|
86 | : `Port ${port}`;
|
87 |
|
88 |
|
89 | switch (error.code) {
|
90 | case 'EACCES':
|
91 | console.error(`${bind} requires elevated privileges`);
|
92 | process.exit(1);
|
93 | break;
|
94 | case 'EADDRINUSE':
|
95 | console.error(`${bind} is already in use`);
|
96 | process.exit(1);
|
97 | break;
|
98 | default:
|
99 | throw error;
|
100 | }
|
101 | }
|
102 |
|
103 |
|
104 |
|
105 |
|
106 | function onListening() {
|
107 | const addr = server.address();
|
108 | const bind = typeof addr === 'string'
|
109 | ? 'pipe ' + addr
|
110 | : 'port ' + addr.port;
|
111 | debug('Server ready');
|
112 | console.log(`Listening on ${bind} \n`);
|
113 | }
|
114 |
|
115 |
|
116 | module.exports.start = start;
|
117 | module.exports.stop = stop;
|