-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
66 lines (52 loc) · 1.52 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
var Url = require('url');
// require node-static
var JohnnysStatic = require('johnnys-node-static'),
http = require('http'),
util = require('util');
// set webroot
var port = process.env.PORT || 8080;
// set file variable
JohnnysStatic.setStaticServer({root: "./public"});
JohnnysStatic.setRoutes(require("./routes.json"))
var apis = require("./lib/api");
// create server
http.createServer(function(req, res) {
// get the url
var pathName = Url.parse(req.url, true).pathname;
// verify if it doesn't end with '/'
if (pathName.slice(-1) !== "/") {
// if yes, add '/'
pathName += "/";
}
// if it exists
if (JohnnysStatic.exists(req, res)) {
// serve the file
JohnnysStatic.serve(req, res, function (err) {
// not found error
if (err.code === "ENOENT") {
res.end("404 - Not found.");
}
// other error
res.end(err.toString());
});
return;
}
// maybe the route is an api url
var api = apis[pathName];
if (typeof api === "function") {
api(req, res);
return;
}
// serve file
JohnnysStatic.serveAll(req, res, function(err, result) {
// check for error
if (err) {
res.writeHead(err.status, err.headers);
res.end();
} else {
console.log('%s - %s', req.url, result.message);
}
});
}).listen(port);
// print some output
console.log('node-static running at http://localhost:%d', port);