-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrouter.js
44 lines (40 loc) · 1.43 KB
/
router.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
var fs = require('fs');
var path = require('path');
var mime = require('./mime').types;
function route(handle, pathname, req, res) {
console.log('About to route a request for ' + pathname);
if ( typeof handle[pathname] === 'function' ) {
handle[pathname](req, res);
} else {
var realPath = 'public' + pathname;
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
var contentType = mime[ext] || 'text/plain';
fs.access(realPath, function(err) {
if ( err ) {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.write('This request URL ' + pathname + ' was not found on this server.');
res.end();
} else {
fs.readFile(realPath, 'binary', function(err, file) {
if ( err ) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.write(err);
res.end();
} else {
res.writeHead(200, {
'Content-Type': contentType
});
res.write(file, 'binary');
res.end();
}
});
}
});
}
}
exports.route = route;