Вообщем после долгих экспериментов как-то переписать все ассинхронно у меня не получилось. ассинхронный код - это вонючая куча из вложенных функций с callback'ами. Синхронный код прост и понятен, асинхронный же сплошь и рядом копипастинг
var KB = 1024;
var MB = 1048576;
var GB = 1073741824;
var SECOND = 1000;
var MINUTE = 60000;
var HOUR = 3600000;
var DAY = 86400000;
var WEEK = 604800000;
var MONTH = 2628000000;
var YEAR = 31536000000;
var ALLOWED_METHODS = ['GET', 'POST'];
var LISTEN_PORT = 8080;
var STATIC_FILES_DIRECTORY = './public';
var MAX_REQUEST_LENGTH = 4 * MB;
var SESSION_NAME = 'sess';
var SESSION_LIFETIME = 20 * MINUTE;
var http = require('http');
var fs = require('fs');
var qs = require('querystring');
var url = require('url');
var mime = require('./mime');
var cookie = require('./cookie');
var template = require('./template');
var session = new cookie.Session(SESSION_NAME, SESSION_LIFETIME);
var routes = {
GET: [
['/', function(rq, rs) {
session.start();
var ctxt = {
'render': template.render,
'title': 'Главная',
'content': 'Привет, мир!'
}
rs.writeHead(202, {'content-type': 'text/html; charset=utf-8'});
rs.render('templates/layot.htm', ctxt);
}],
['/index.htm', function(rq, rs) {
rs.writeHead(302, {location: '/'})
rs.end();
}],
['/cookie.htm', function(rq, rs) {
session.start();
rs.end(JSON.stringify(rq.cookie));
}]
],
POST: []
};
// еще 200 строк кода пропущены
Модуль шаблонов
// [url]http://ejohn.org/blog/javascript-micro-templating/[/url] идею отсюда позаимствовал
var fs = require('fs');
var OPEN_TAG = '<%';
var CLOSING_TAG = '%>';
var cache = {/*[$compiled, $timestamp]*/};
function compile(s) {
var c = [],
p0 = 0,
p1,
m;
while (true) {
p1 = s.indexOf(OPEN_TAG, p0);
if (p1 == -1) {
p1 = s.length;
}
if (p0 < p1) {
c.push('out+=' + JSON.stringify(s.slice(p0, p1)));
}
if (p1 == s.length) {
break;
}
p0 = p1 + OPEN_TAG.length;
p1 = s.indexOf(CLOSING_TAG, p0);
if (p1 == -1) {
p1 = s.length;
}
m = s.slice(p0, p1);
c.push(m[0] == '=' ? 'out+=' + m.slice(1) : m);
p0 = p1 + CLOSING_TAG.length;
if (s[p0] == '\r') {
++p0;
}
if (s[p0] == '\n') {
++p0;
}
}
return c.join(';');
}
var render = module.exports.render = function(fn, obj) {
try {
if (!cache[fn] || new Date(fs.statSync(fn).mtime).getTime() > cache[fn][1]) {
cache[fn] = [
compile(fs.readFileSync(fn, 'utf-8')),
new Date().getTime()
];
}
return new Function('context', 'var out="";with(context){' + cache[fn][0] + '}return out')(obj || {});
}
catch (e) {
console.log(e);
}
}
require('http').ServerResponse.prototype.render = function(fn, obj) {
this.end(render(fn, obj));
}
Шаблоны все, которые использовал
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
</body>
</html>
HTML]
[HTML]
<%= render('templates/header.htm', context) %>
<div class="container">
<h1 class="title"><%= title %></h1>
<div class="content"><%= content %></div>
</div>
<%= render('templates/footer.htm') %>
На выходе
<!DOCTYPE html>
<html>
<head>
<title>Главная</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div class="container">
<h1 class="title">Главная</h1>
<div class="content">Привет, мир!</div>
</div>
</body>
</html>
Содержимое кэша
{ 'templates/layot.htm':
[ 'out+= render(\'templates/header.htm\', context) ;out+=" <div class=\\"container\\">\\r\\n <h1 class=\\"title\\">";out+= title ;out+="</h1>\\r\\n <div class=\\"content\\">";out+= content ;out+="</div>\\r\\n </div>\\r\\n";out+= render(\'templates/footer.htm\') ',
1354106612748 ],
'templates/header.htm':
[ 'out+="<!DOCTYPE html>\\r\\n<html>\\r\\n <head>\\r\\n <title>";out+= title ;out+="</title>\\r\\n <meta http-equiv=\\"Content-Type\\" content=\\"text/html; charset=utf-8\\">\\r\\n </head>\\r\\n <body>\\r\\n"',
1354106612748 ],
'templates/footer.htm': [ 'out+=" </body>\\r\\n</html>\\r\\n"', 1354106612758 ] }