|
| 1 | +// Dependencies |
| 2 | +var http = require('http'), |
| 3 | + fs = require('fs'); |
| 4 | + |
| 5 | +// Cache |
| 6 | +var cache = {}; |
| 7 | + |
| 8 | +// HTTP Server |
| 9 | +http.createServer(function (req, res) { |
| 10 | + |
| 11 | + // Parse cookies |
| 12 | + var cookie = req.headers.cookie, |
| 13 | + cookies = {}; |
| 14 | + if (cookie) cookie.split(';').forEach(function(item) { |
| 15 | + var parts = item.split('='); |
| 16 | + cookies[(parts[0]).trim()] = (parts[1] || '').trim(); |
| 17 | + }); |
| 18 | + |
| 19 | + // Logging |
| 20 | + var date = new Date().toISOString(); |
| 21 | + console.log([date, req.method, req.url].join(' ')); |
| 22 | + |
| 23 | + // Serve from cache |
| 24 | + if (cache[req.url] && req.method === 'GET') { |
| 25 | + res.writeHead(200); |
| 26 | + res.end(cache[req.url]); |
| 27 | + } else { |
| 28 | + |
| 29 | + // Routing |
| 30 | + if (req.url === '/') { |
| 31 | + if (req.method === '') |
| 32 | + response.writeHead(200, { |
| 33 | + 'Set-Cookie': 'mycookie=test', |
| 34 | + 'Content-Type': 'text/plain' |
| 35 | + }); |
| 36 | + var ip = req.connection.remoteAddress; |
| 37 | + res.write('<h1>Welcome</h1>Your IP: ' + ip); |
| 38 | + res.end('<pre>' + JSON.stringify(cookies) + '</pre>'); |
| 39 | + } else if (req.url === '/person') { |
| 40 | + if (req.method === 'GET') { |
| 41 | + |
| 42 | + // Some business logic |
| 43 | + fs.readFile('./person.json', function(err, data) { |
| 44 | + if (!err) { |
| 45 | + var obj = JSON.parse(data); |
| 46 | + obj.birth = new Date(obj.birth); |
| 47 | + var difference = new Date() - obj.birth; |
| 48 | + obj.age = Math.floor(difference / 31536000000); |
| 49 | + delete obj.birth; |
| 50 | + var data = JSON.stringify(obj); |
| 51 | + cache[req.url] = data; |
| 52 | + |
| 53 | + // HTTP reply |
| 54 | + res.writeHead(200); |
| 55 | + res.end(data); |
| 56 | + } else { |
| 57 | + res.writeHead(500); |
| 58 | + res.end('Read error'); |
| 59 | + } |
| 60 | + }); |
| 61 | + } else if (req.method === 'POST') { |
| 62 | + |
| 63 | + // Receiving POST data |
| 64 | + var body = []; |
| 65 | + request.on('data', function(chunk) { |
| 66 | + body.push(chunk); |
| 67 | + }).on('end', function() { |
| 68 | + var data = Buffer.concat(body).toString(); |
| 69 | + fs.writeFile('./person.json', data, function(err) { |
| 70 | + if (!err) { |
| 71 | + res.writeHead(200); |
| 72 | + res.end('File saved'); |
| 73 | + } else { |
| 74 | + res.writeHead(500); |
| 75 | + res.end('Write error'); |
| 76 | + } |
| 77 | + }); |
| 78 | + }); |
| 79 | + } |
| 80 | + } else { |
| 81 | + res.writeHead(404); |
| 82 | + res.end('Path not fount'); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | +}).listen(80); |
0 commit comments