-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path2-wait-a-bit.js
More file actions
73 lines (63 loc) · 1.56 KB
/
2-wait-a-bit.js
File metadata and controls
73 lines (63 loc) · 1.56 KB
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
'use strict';
const http = require('node:http');
const connections = new Map();
const SERVER_PORT = 8000;
const LONG_RESPONSE = 60000;
const SHUTDOWN_TIMEOUT = 5000;
const server = http.createServer((req, res) => {
console.log('New request');
connections.set(res.connection, res);
setTimeout(() => {
res.end('Example output');
}, LONG_RESPONSE);
});
server.on('connection', (connection) => {
console.log('New connection');
connection.on('close', () => {
console.log('Close');
connections.delete(connection);
});
});
server.listen(SERVER_PORT);
const showConnections = () => {
console.log('Connection:', [...connections.values()].length);
for (const connection of connections.keys()) {
const { remoteAddress, remotePort } = connection;
console.log(` ${remoteAddress}:${remotePort}`);
}
};
const closeConnections = () => {
for (const [connection, res] of connections.entries()) {
connections.delete(connection);
res.end('Server stopped');
connection.destroy();
}
};
const freeResources = (callback) => {
console.log('Free resources');
callback();
};
const gracefulShutdown = (callback) => {
server.close((error) => {
if (error) {
console.log(error);
process.exit(1);
}
});
setTimeout(() => {
freeResources(() => {
closeConnections();
callback();
});
}, SHUTDOWN_TIMEOUT);
};
process.on('SIGINT', () => {
console.log();
console.log('Graceful shutdown');
showConnections();
gracefulShutdown(() => {
showConnections();
console.log('Bye');
process.exit(0);
});
});