Created
April 10, 2010 01:26
-
-
Save mumrah/361752 to your computer and use it in GitHub Desktop.
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 fs = require('fs'); | |
var url = require('url'); | |
var sys = require('sys'); | |
var http = require('http'); | |
require('./ejs'); // EJS, http://embeddedjs.com/ | |
/* | |
* Server-side controller methods | |
*/ | |
var routes = new function(){ | |
this.routes = {}; | |
this.register = function(route, callback){ | |
this.routes[route] = callback; | |
} | |
} | |
routes.register('/', function(env){ | |
var tmpl = fs.readFileSync('base.html'); // An minimal HTML template, puts $head_js in the <head> | |
var html = new EJS({text: tmpl}).render({head_js: client.toString()}); | |
env.res.writeHead(200, {'Content-Type': "text/html"}); | |
env.res.write(html); | |
env.res.close(); | |
}); | |
routes.register('/test',function(env){ | |
env.res.writeHead(200, {'Content-Type': "text/plain"}); | |
env.res.write("Hello, Indeed!"); | |
env.res.close(); | |
}); | |
routes.register('/favicon.ico',function(env){ | |
env.res.writeHead(200, {'Content-Type': "image/png"}); | |
env.res.close(); | |
}); | |
/* | |
* Client-side functions | |
*/ | |
var client = new function(){ | |
this.funcs = []; | |
this.register = function(name, func){ | |
this.funcs.push(func); | |
var func_str = func.toString(); | |
func.toString = function(){ return "var " + name + " = " + func_str + ";"} | |
} | |
this.toString = function(){ | |
var js_out = ""; | |
this.funcs.forEach(function(func){ | |
js_out += func.toString(); | |
}); | |
return js_out; | |
} | |
} | |
client.register('foo',function(){ | |
var div = $(document.body).append("<div>Hello, World</div>"); | |
div.bind('click',function(e){ | |
$.ajax({ | |
url: '/test', | |
success: function(d){ $(div).append("<div>#"+d+"#</div>"); } | |
}); | |
}); | |
}); | |
client.register('onload',function(){ | |
foo(); | |
}); | |
http.createServer(function(req, res){ | |
var url_parse = url.parse(req.url,true); | |
var env = { | |
req : req, | |
res : res, | |
path : url_parse.pathname, | |
url_params : (url_parse.query) ? url_parse.query : {} | |
}; | |
if(req.method == 'GET') { | |
for(route in routes.routes) { | |
if(env.path == route) { | |
routes.routes[route].call(this, env); | |
} | |
} | |
} | |
}).listen(8000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Little example of using Node.js to serve up client side code along side server side code. Here's the template that was used: