Skip to content

Instantly share code, notes, and snippets.

@mocheng
Created June 9, 2011 10:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mocheng/1016468 to your computer and use it in GitHub Desktop.
Save mocheng/1016468 to your computer and use it in GitHub Desktop.
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