backend.js
1.6 KB
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
var http = require('http'),
fs = require('fs'),
path = require('path'),
director = require('../../../lib/director'),
index;
fs.readFile(path.join(__dirname, '..', 'html5-routes-harness.html'), function (err, data) {
if (err) {
throw err;
}
index = data;
});
var CONTENT_TYPES = {
'.js' : 'text/javascript',
'.css' : 'text/css'
};
var dirname = path.dirname(module.uri);
// Dummy file server
function fileServer(folder, file) {
var root = path.resolve(__dirname, '..');
if (folder === 'build' || folder === 'node_modules') {
root = path.resolve(root, '..', '..');
}
if (file === undefined) {
file = folder;
folder = '.';
}
var filepath = path.resolve(root, folder, file);
var res = this.res;
(fs.exists || path.exists)(filepath, function (exists) {
if (exists) {
fs.readFile(filepath, function (err, data) {
if (err) {
res.writeHead(404);
res.end();
}
res.writeHead(200, {'Content-Type': CONTENT_TYPES[path.extname(filepath)]});
res.end(data);
});
} else {
res.writeHead(404);
res.end();
}
});
}
var router = new director.http.Router({
'/files': {
'/:folder': {
'/(.+)': {
get: fileServer
},
get: fileServer
}
}
});
var server = http.createServer(function (req, res) {
router.dispatch(req, res, function (err) {
if (err && req.url !== '/favicon.ico') {
// By default just reply with the index page
this.res.writeHead(200, {'Content-Type': 'text/html'});
this.res.end(index);
}
});
});
server.listen(8080);