-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
50 lines (43 loc) · 1.19 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
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
function start(route, handle) {
var port = process.env.PORT || 1337;
function onRequest(req, res) {
var filePath = '.' + req.url;
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
var pathname = url.parse(req.url).pathname;
fs.exists(filePath, function(exists) {
if(exists) {
// serve up the file directly
fs.readFile(filePath, function(error, content) {
if(error) {
res.writeHead(500);
res.write('error loading file: ' + filePath);
res.end();
} else {
console.log('successfully served ' + filePath);
res.writeHead(200, {'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
} else {
// route
route(handle, pathname, res, req);
}
});
}
http.createServer(onRequest).listen(port);
console.log('Server has started.');
}
exports.start = start;