-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
server.js
102 lines (86 loc) · 3 KB
/
server.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict';
/**
* Module dependencies.
*/
const config = require('wild-config');
const log = require('npmlog');
const https = require('https');
const http = require('http');
const pem = require('pem');
const db = require('./lib/db');
const port = config.www.port;
const host = config.www.host;
if (config.title) {
process.title = config.title;
}
log.level = config.log.level;
// Initialize database connection
db.connect(err => {
if (err) {
log.error('Db', 'Failed to setup database connection');
return process.exit(1);
}
const app = require('./app'); // eslint-disable-line global-require
app.set('port', port);
/**
* Create HTTP server.
*/
let getServer = next => {
if (config.www.secure) {
return pem.createCertificate({ days: 1, selfSigned: true }, (err, keys) => {
if (err) {
throw err;
}
let server = https.createServer({ key: keys.serviceKey, cert: keys.certificate }, app);
return next(null, server);
});
}
next(null, http.createServer(app));
};
getServer((err, server) => {
if (err) {
throw err;
}
server.on('error', err => {
if (err.syscall !== 'listen') {
throw err;
}
let bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
// handle specific listen errors with friendly messages
switch (err.code) {
case 'EACCES':
log.error('Express', '%s requires elevated privileges', bind);
return process.exit(1);
case 'EADDRINUSE':
log.error('Express', '%s is already in use', bind);
return process.exit(1);
default:
throw err;
}
});
server.on('listening', () => {
let addr = server.address();
let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
log.info('Express', 'WWW server listening on %s', bind);
if (config.group) {
try {
process.setgid(config.group);
log.info('Service', 'Changed group to "%s" (%s)', config.group, process.getgid());
} catch (E) {
log.error('Service', 'Failed to change group to "%s" (%s)', config.group, E.message);
return process.exit(1);
}
}
if (config.user) {
try {
process.setuid(config.user);
log.info('Service', 'Changed user to "%s" (%s)', config.user, process.getuid());
} catch (E) {
log.info('Service', 'Failed to change user to "%s" (%s)', config.user, E.message);
return process.exit(1);
}
}
});
server.listen(port, host);
});
});