-
Notifications
You must be signed in to change notification settings - Fork 1
/
requestHandler.js
executable file
·114 lines (100 loc) · 3.12 KB
/
requestHandler.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
103
104
105
106
107
108
109
110
111
112
113
114
const qs = require('querystring');
const path = require('path');
const fs = require('fs');
//Print out error messages
function printError(error){
console.error("Error: " + error.message);
}
function formRequest(req, res){
if (req.method === 'POST'){
var body = '';
req.on('data', function( data){
body += data;
if (body.length > 1e6){
req.connection.destroy();
}
});
req.on('end', function(){
try{
var POST = qs.parse(body);
console.log(POST);
}catch (error){
printError(error);
}
});
req.on('error', printError);
}
}
function home(req, res) {
var filePath = '.' + req.url;
if (filePath == './'){
filePath = './index.html';
}
var extension = path.extname(filePath).toLowerCase();
var contentType = 'text/html';
switch(extension){
case '.svg':
contentType = 'image/svg+xml';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.map':
contentType = 'application/json';
break;
case '.css':
contentType = 'text/css';
break;
case '.jpg':
contentType = 'image/jpeg';
break;
case '.json':
contentType = 'application/json';
break;
case '.html':
contentType = 'text/html';
break;
case '.png':
contentType = 'image/png';
break;
case '.woff2':
contentType = 'application/font-woff2';
break;
case '.woff':
contentType = 'application/x-font-woff';
break;
case '.ttf':
contentType = 'application/x-font-truetype';
break;
}
try {
fs.readFile(filePath, function (error, content) {
if (error) {
if (error.code == 'ENOENT') {
printError({message:"location:" + error.path + " errorCode:" + error.errno});
fs.readFile('./error/404.html', function (error, content) {
if(error){
printError({message:"location:" + error.path + " errorCode:" + error.errno});
throw (error);
}else {
res.writeHead(200, {'Content-Type': contentType});
res.end(content, 'utf-8');
}
});
} else {
printError({message:"location:" + error.path + " errorCode:" + error.errno});
res.writeHead(500);
res.write("Error: " + error.description + '..\n Path: ' + error.path);
res.end();
}
} else {
res.writeHead(200, {'Content-Type': contentType});
res.end(content, 'utf-8');
}
})
}catch (error){
printError(error);
}
}
module.exports.home = home;
module.exports.formRequest = formRequest;