-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (46 loc) · 1.66 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
/*
like-server (https://npmjs.com/package/like-server)
Copyright 2019 Lucas Barrena
Licensed under MIT (https://github.com/LuKks/like-server)
*/
'use strict';
if (!extendSocket(require('net'))) {
extendHttp(require('http'));
extendHttp(require('https'), true);
}
function extendSocket (base) {
if (typeof base.Socket.prototype.terminated !== 'undefined') return true;
base.Socket.prototype.requests = 0;
base.Socket.prototype.terminated = false;
base.Socket.prototype.terminate = function () {
this.terminated = true;
return this.requests ? this.emit('terminate') : this.end(this.destroy);
}
let create = base.createServer;
base.createServer = function (options, listener) {
return create.call(base, options, listener).prependListener('connection', connection);
}
base.Server.prototype.terminated = false;
let close = base.Server.prototype.close;
base.Server.prototype.close = function (callback) {
close.call(this, callback);
this.terminated = true;
return this.emit('terminate');
}
}
function connection (socket) {
let term = () => socket.terminate();
this.once('terminate', term);
socket.once('close', () => this.removeListener('terminate', term));
}
function extendHttp (base, secure) {
let create = base.createServer;
base.createServer = function (options, listener) {
return create.call(base, options, listener)
.prependListener(secure ? 'secureConnection' : 'connection', connection)
.prependListener('request', function (req, res) {
req.connection.requests++;
res.on('finish', () => !--req.connection.requests && this.terminated && req.connection.end(req.connection.destroy));
});
}
}