Created
June 9, 2011 10:14
-
-
Save mocheng/1016468 to your computer and use it in GitHub Desktop.
Simple MVC demo in Node.js
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
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<meta http-equiv="content-type" content="text/html; charset=utf-8"> | |
<title>MVC Demo</title> | |
</head> | |
<body> | |
{{name}} is {{title}}. | |
</body> | |
</html> |
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 PORT = 8000, | |
sys = require('sys'), | |
http = require('http'), | |
fs = require('fs'), | |
_ = require('underscore'), | |
mustache = require('mustache'); | |
var actions = []; | |
actions.push({ | |
path: "/", | |
template: "index.html", | |
view: { | |
title: "F2E", | |
name: 'Morgan' | |
} | |
}); | |
http.createServer(function(req, res) { | |
var action = _(actions).chain().select(function(a) {console.log(req.url); return req.url === a.path}).first().value(); | |
console.log(action); | |
if (_.isEmpty(action)) { | |
res.writeHeader(404, {'Content-Type': 'text/plain'}); | |
res.end("Error"); | |
} else { | |
fs.readFile('./' + action.template, function(err, data) { | |
var template = data.toString(); | |
res.writeHeader(200, {'Content-Type': 'text/html'}); | |
res.write(mustache.to_html(template, action.view)); | |
res.end(); | |
}); | |
} | |
}).listen(PORT); | |
console.log('Server is listening on port ' + PORT + '...'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment