Skip to content

Instantly share code, notes, and snippets.

@mocheng

mocheng/index.html

Created Jun 9, 2011
Embed
What would you like to do?
Simple MVC demo in Node.js
<!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>
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