-
Notifications
You must be signed in to change notification settings - Fork 0
/
responseHandler.js
111 lines (97 loc) · 2.35 KB
/
responseHandler.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
var fs = require('fs');
var path = require('path');
var util = require('util');
var buffer = require('buffer');
/*
* Returns the path of the file in the server file system, according to the root folder.
*/
function filePath(originalPath,rootResource,rootFolder){
if(originalPath === '/'){
return "./index.html";
}
var ResourceRegex = new RegExp(rootResource);
var isAllowed = ResourceRegex.test(originalPath);
if(isAllowed){
var realPath;
if(rootResource === '/'){
realPath = originalPath.substr(1);
}
else{
realPath = originalPath.split(rootResource)[1];
}
realPath = path.normalize(realPath);
return realPath;
}
else{
return null;
}
}
/*
* Responds to client the http requests.
*/
function createResponse(rootResource,rootFolder,req,res,next){
var file = filePath(req.path,rootResource,rootFolder); // get the path of
fs.stat(file,function(err,stats){
if(err === null){
if(stats.isFile()){
res.status(200);
res.httpRes.sendDate = true;
var contentTypeResult = contentType(file);
res.set("Content-Type",contentTypeResult);
var filesize = getFileSize(stats);
res.set("Content-Length",filesize);
var fileAsAstream = fs.createReadStream(file);
fileAsAstream.on('readable',function(){
var buf;
while((buf = fileAsAstream.read()) != null){
res.send(buf);
}
});
}
}
else{
next();
}
});
}
/*
* Returns the size of the requested file, for the content-length field in the response.
*/
function getFileSize(stats){
var fileDetailsStr = util.inspect(stats);
var sizeReg = new RegExp("size: [0-9]*");
var sizeSection = sizeReg.exec(fileDetailsStr)[0];
var size = sizeSection.split(' ')[1];
return size;
}
/*
* Returns the content-type value as should be according to the requested file extension.
*/
function contentType(filePath){
var extension = path.extname(filePath);
if(extension === ".txt"){
return "text/plain";
}
if(extension === ".js"){
return "application/javascript";
}
if(extension === ".json"){
return "application/json";
}
if(extension === ".html"){
return "text/html";
}
if(extension === ".css"){
return "text/css";
}
if(extension === ".jpg"){
return "image/jpeg";
}
if(extension === ".gif"){
return "image/gif";
}
if(extension === ".png"){
return "image/png";
}
}
exports.createResponse = createResponse;