-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
168 lines (139 loc) · 4.13 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
const util = require('util');
const qs = require('querystring');
const url = require('url');
const fs = require('fs');
const path = require('path');
const superHandlers = {};
const config = {}
function Use(Utility){
if(Utility.type === 'router'){
for(let method in Utility.handlers){
superHandlers[method] = Utility.handlers[method];
}
}
if(Utility.type === 'static'){
config.static = Utility.setup();
}
}
function isPathWithParams(path){
let pathWithParamsRegexp = /(\/:.*?)+/gi;
return pathWithParamsRegexp.test(path);
}
function removeFalsePositives(array){
return array.filter((item) => {
if(Boolean(item) == true){
return true;
}
return false;
})
}
function Serve(req, res){
// check for static file
if(isStaticFile(req.url)){
if(isValidStaticFile(req.url)){
return sendFile(req.url, res);
} else {
res.statusCode = 404;
return res.end(`${req.url} Not found`)
}
}
req.params = {}
req.query = qs.parse(req.url.slice(req.url.indexOf('?')+1,));
let pathname = url.parse(req.url).pathname
if(superHandlers[pathname]){
if(req.method.toLowerCase() == superHandlers[pathname].method){
return superHandlers[pathname].handler(req, res);
}
}
for(let path in superHandlers){
if(isPathWithParams(path)){
let pathParts = removeFalsePositives(path.split('/'));
let urlParts = removeFalsePositives(pathname.split('/'));
if(pathParts.length != urlParts.length){
continue;
}
// compare parts
for(let part in pathParts){
if(pathParts[part].indexOf(':') == 0){
req.params[pathParts[part].slice(1,)] = urlParts[part]
continue;
}
if(pathParts[part] != urlParts[part]){
break;
}
}
return superHandlers[path].handler(req, res);
}
if(superHandlers[path].type == 'regexp'){
if(superHandlers[path].path.test(pathname.slice(1,)) == true){
return superHandlers[path].handler(req, res);
}
}
}
res.statusCode = 404;
return res.end(`${req.url} Not found`)
}
function Router(){
return {
handle : function(path, method, handler){
this.handlers[path] = {
method: method.toLowerCase(),
handler: handler,
path: path,
type: typeof(path) == 'string' ? 'string' : util.types.isRegExp(path) == true ? 'regexp' : null,
}
},
handlers : {},
type: 'router',
}
}
function isStaticFile(url){
console.log("extension name", path.extname(url))
return path.extname(url);
}
function isValidStaticFile(url){
let isValid = true;
try{
fs.accessSync(`${config.static}${url.split('/').join(path.sep)}`, fs.constants.R_OK)
} catch(exc){
console.log("file is not accessible", exc)
return false;
}
return isValid;
}
function sendFile(url, res){
const fileAddress = `${config.static}${url.split('/').join(path.sep)}`;
// fs.readFile(fileAddress, function(err, fileData){
// if(err){
// return res.end("Error reading file")
// }
// return res.end(fileData);
// })
const readStream = fs.createReadStream(fileAddress);
// Handle stream events --> data, end, and error
readStream.on('data', function(chunk) {
res.write(chunk);
});
readStream.on('end',function() {
res.end();
});
readStream.on('error', function(err) {
res.statusCode = 404;
res.end(`${url} Not found`)
});
}
function Static(publicFolder){
let staticDirectory = publicFolder;
return {
setup: function(){
return `${process.cwd()}${path.sep}${staticDirectory}`;
},
type: 'static',
}
}
module.exports = {
Router: Router,
Serve: Serve,
Use: Use,
Static: Static,
}