Skip to content

Instantly share code, notes, and snippets.

@esommer
Created November 26, 2013 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esommer/7668128 to your computer and use it in GitHub Desktop.
Save esommer/7668128 to your computer and use it in GitHub Desktop.
Solution to exercise from Mary's seminar: (we didn't need to be "return"ing all our outputs, just executing them is enough.
var http = require('http');
var fs = require('fs');
var DAY = "day";
var NIGHT = "night";
var server = {
getFile : function (path, filetype, res) {
fs.readFile(__dirname + path, 'utf8', function (err, data) {
res.writeHead(200, { 'Content-Type': filetype });
res.end(data);
});
},
routes : {
"/" : function (res) {
this.getFile('/index.html', 'text/html', res);
},
"/client.js" : function (res) {
this.getFile('/client.js', 'application/javascript', res);
},
"/canvas-renderer.js" : function (res) {
this.getFile('/canvas-renderer.js', 'application/javascript', res);
},
"/time.json" : function (res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end('{ "time": "' + this.getTimeOfDay(new Date().getHours()) + '" }');
}
},
getTimeOfDay : function (hour) {
return hour > 6 && hour < 20 ? DAY : NIGHT;
},
requestHandler: function (req, res) {
if (Object.keys(this.routes).indexOf(req.url) !== -1) {
this.routes[req.url].call(this, res);
}
else {
res.writeHead(404, { 'Content-Type': 'text/plain'});
res.end('Not found. Apologies!');
}
}
};
http.createServer(server.requestHandler).listen(4000);
exports.server = server;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment