-
Notifications
You must be signed in to change notification settings - Fork 1
/
create-listener.js
97 lines (83 loc) · 2.72 KB
/
create-listener.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
var fs = require('fs');
var fetchFile = function(fileName, response) {
fs.readFile(fileName, function (err, data) {
if (err) {
console.log(err);
response.writeHeader(404);
// this crashes the server in some macs...
//response.write(err.toString());
}else{
var contentType = guessContentType(fileName);
console.log(fileName+" "+contentType["Content-Type"]);
response.writeHeader(200, contentType);
response.write(data);
}
response.end();
});
};
var guessContentType = function(fileName){
if(/.+\.js$/.test(fileName)){
return {"Content-Type": "text/javascript"};
}else if(/.+\.json$/.test(fileName)){
return {"Content-Type": "application/json"};
}else if(/.+\.css$/.test(fileName)) {
return {"Content-Type": "text/css"};
}else {
return {"Content-Type": "text/html"};
}
};
var saveFile = function(request, response, pathname){
var fullBody = '';
request.on('data', function(chunk) {
fullBody += chunk.toString();
});
request.on('end', function() {
// empty 200 OK response for now
fs.writeFile(pathname, decodeURIComponent(fullBody), function(err) {
if(err) {
console.log(err);
response.writeHead(500, "OUPS", {'Content-Type': 'text/html'});
response.end();
} else {
console.log("The file was saved!" + pathname);
response.writeHead(200, "OK", {'Content-Type': 'text/html'});
response.end();
}
});
});
};
var readDirectory = function (path, response){
fs.readdir(path, function(err, files){
if(err) {
console.log(err);
response.writeHead(500, "OUPS", {'Content-Type': 'text/html'});
response.end();
} else {
response.writeHeader(200, {'Content-Type': 'application/json'});
response.write(JSON.stringify(files));
response.end();
}
});
};
module.exports = function(rootStaticFiles){
rootStaticFiles = rootStaticFiles || './public/';
return function(request, response) {
var pathname = require('url').parse(request.url).pathname;
console.log("get me "+pathname);
var dirRegex = /^\/(animations|assemblages)\/$/,
matchingDir = pathname.match(dirRegex);
if(matchingDir && request.method === "GET"){
readDirectory(rootStaticFiles + matchingDir[0], response);
}else if (request.method === "GET"){
if (pathname === "/" || pathname.substr(0,12) === "/assemblage/"){
pathname = "/index.html";
}
fetchFile(rootStaticFiles + pathname, response);
}else if (request.method === "POST"){
saveFile(request, response, rootStaticFiles + pathname);
}else{
response.writeHeader(501);
response.end();
}
};
};