-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (84 loc) · 2.25 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
// global
var static = require('node-static')
// static server object
, staticServer
// routes object
, routes = {}
// module
, objToExport = {};
// set the static server
objToExport.setStaticServer = function (options) {
return staticServer = new(static.Server)(options.root);
};
// set routes
objToExport.setRoutes = function (routesObj, callback) {
var objRoutes = Object.keys (routesObj);
for (var i = 0; i < objRoutes.length; ++i) {
var route = objRoutes[i]
, cRoute = routesObj[route]
;
if (cRoute.slice(-1) !== "/") {
delete routesObj[route];
if (route !== "/") {
route += "/";
}
routesObj[route] = cRoute;
if (cRoute && cRoute.constructor.name === "String") {
routesObj[route] = {
url: cRoute
}
}
}
}
// set routes object
routes = routesObj;
// if callback is defined, call it!
callback ? callback(null, routes) : "";
// also, return routes
return routes;
};
function getRoute (url) {
// verify if it doesn't end with '/'
if (url.slice(-1) !== "/") {
// if yes, add '/'
url += "/";
}
// get route
var route = routes[url];
// and return it
return route;
}
// route exists
// TODO Options?
objToExport.exists = function (req, res) {
// get the route object from routes
var route = getRoute(req.url);
// if it exists
if (route && route.url) {
// return true
return true;
}
// else, return false
return false;
}
// serve
// TODO options
objToExport.serve = function (req, res, callback) {
// force callback to be a function
callback = callback || function () {};
// get route
var route = getRoute(req.url)
// get the promise
, promise = staticServer.serveFile(route.url, 200, {}, req, res);
// if an error appears, callback it
promise.on("error", callback);
// and return the promise
return promise;
};
// serve any file
objToExport.serveAll = function (req, res, callback) {
// serve any file
staticServer.serve(req, res, callback);
};
// export the module
module.exports = objToExport;