Created
October 30, 2012 03:18
-
-
Save lkptrzk/3978123 to your computer and use it in GitHub Desktop.
minimal nodejs server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
util = require('util'), | |
url = require('url'); | |
var handlers = {}; | |
handlers.homepage = function (request, response) { | |
response.writeHead(200, { 'Content-type': 'text/plain' }); | |
response.write('homepage goes here.'); | |
}; | |
function route (path) { | |
var routes = [ | |
{ pattern: /^[\/]+$/, | |
handler: 'homepage' | |
} | |
], | |
i = 0, len = routes.length, match = null; | |
for (; i < len; i++) { | |
if ((match = routes[i].pattern.exec(path)) !== null) { | |
return function (request, response) { | |
var args = [request, response].concat(match.slice(1)); | |
try { | |
handlers[routes[i].handler].apply(null, args); | |
} catch (ex) { | |
throw ex; | |
} | |
}; | |
} | |
} | |
} | |
http.createServer(function (request, response) { | |
var handler = route(url.parse(request.url).pathname); | |
if (typeof handler === 'undefined') { | |
response.statusCode = 404; | |
} else { | |
try { | |
handler(request, response); | |
} catch (ex) { | |
console.error(util.format('error:', new Date(), ex.message || ex)); | |
response.statusCode = 500; | |
} | |
} | |
response.end(); | |
}).listen(process.argv[2] || 8000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment