forked from kat4/meow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
73 lines (63 loc) · 2.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//declaring handler
var fs = require('fs');
var index = fs.readFileSync(__dirname + '/public/index.html');
var RedisMeow = require('./redis.js');
var Server = (function() {
function handler(req, res) {
var url = req.url;
var urlArray = url.split('/');
if (req.method === 'GET') {
if (url === '/') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(index);
} else if (urlArray[1] == 'meows') {
RedisMeow.getMeow(function(data) {
res.end(data);
});
} else {
fs.readFile(__dirname + '/public' + req.url, function(err, file) {
if (err) {
res.writeHead(404);
res.end('arm broken');
} else {
var ext = req.url.split('.')[1];
res.writeHead(200, {
'Content-Type': 'text/' + ext
});
res.end(file);
}
});
}
} else if (req.method === 'POST') {
var body = '';
req.on('data', function(chunk) {
body += chunk;
//what if there are more chunks, you should end the request in the "end" handler
//console.log("chunk", body);
});
//You should send a response anyway in the end handler
req.on('end', function() {
//store stuff in a list in redis
RedisMeow.postMeow(body, function() {
RedisMeow.getMeow(function(data) {
res.end(data);
});
});
});
} else if (req.method === 'DELETE') {
var key = urlArray[1];
console.log("delete request working");
RedisMeow.deleteMeow(key, function() {
RedisMeow.getMeow(function(data) {
res.end(data);
});
});
}
}
return {
handler: handler
};
}());
module.exports = Server;