-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
69 lines (59 loc) · 1.53 KB
/
index.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
const printServer = require('./lib/printServer');
const parseArguments = require('./lib/getOptionsFromArgv.js');
const connections = require('./lib/getSetOfSockets.js')();
const CONFIG = parseArguments(process.argv);
if (CONFIG.usageText !== null) {
console.log(`USAGE: ${path.basename(module.filename)} ${CONFIG.usageText}\n`);
process.exit(0); // eslint-disable-line no-process-exit
}
const server = printServer(CONFIG);
if (!server) {
process.exit(-1);
}
server.listen(CONFIG.port, CONFIG.hostname, null, onServerListening);
// Keep track of connections, to enforce killing them when server must be stopped.
server.on('connection', connections.onNewConnection);
[
'SIGHUP',
'SIGINT',
'SIGQUIT',
'SIGILL',
'SIGTRAP',
'SIGABRT',
'SIGBUS',
'SIGFPE',
'SIGUSR1',
'SIGSEGV',
'SIGUSR2',
'SIGTERM'
].forEach(signal => process.once(signal, onServerSignal));
/**
* Net server
*
* @typedef external:net.Server
* @see {@link https://nodejs.org/api/net.html#net_class_net_server}
*/
/**
* Output some info about server that's listening.
*
* @private
* @this external:net.Server
*/
function onServerListening () {
const address = this.address();
console.log(`Listening on http://${address.address}:${address.port}`);
}
/**
* Quickly stop server on signal.
*
* @private
* @param {string} signal
*/
function onServerSignal (signal) {
console.log(`Got ${signal}, stopping server...`);
server.close(() => {
console.log('Server stopped. Bye!');
process.exit(0); // eslint-disable-line no-process-exit
});
connections.closeAll();
}