-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
executable file
·100 lines (84 loc) · 2.36 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
#!/usr/bin/env node
'use strict';
const http = require('http');
const path = require('path');
const fs = require('fs');
const console = require('console');
function echo(request, response) {
const data = {
ip: request.connection.remoteAddress,
method: request.method,
url: request.url,
body: '',
headers: request.headers,
};
request.on('data', buffer => {
data.body += buffer.toString();
});
request.on('end', () => {
const body = JSON.stringify(data, null, 2);
response.setHeader('Content-Type', 'application/json');
response.end(body);
});
}
function error(response) {
response.statusCode = 500;
response.end('500 SERVER ERROR');
}
function crash(response) {
response.statusCode = 500;
response.socket.destroy();
}
function serveFromDisk(pathname, response) {
let safePath = pathname.replace(/\.\./g, '').replace(/^\/+/, '');
if (safePath === '') safePath = 'index.html';
const filePath = path.resolve(__dirname, 'public', safePath);
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
let contentType = 'text/html';
if (filePath.endsWith('.js')) {
contentType = 'application/javascript';
}
response.setHeader('Content-Type', contentType);
fs.createReadStream(filePath).pipe(response);
} else {
response.statusCode = 404;
response.end('File Not Found');
}
}
function createServer() {
return http.createServer((request, response) => {
const { pathname } = new URL(request.url, `http://${request.headers.host}`);
switch (pathname) {
case '/echo':
return echo(request, response);
case '/error':
return error(response);
case '/crash':
return crash(response);
case '/blackhole':
return null;
default:
return serveFromDisk(pathname, response);
}
});
}
const testApp = (module.exports = {
listen: function listen(port, callback) {
this.server = createServer();
this.server.listen(port, callback);
},
kill: function kill(callback) {
this.server.close(callback);
this.server = null;
},
});
if (module === require.main) {
if (process.env.never_listen) {
console.log('Refusing to listen');
setTimeout(() => {}, 100000);
} else {
testApp.listen(process.env.PORT || 4003, function onListen() {
console.log('Listening on port %j', this.address().port);
});
}
}