Permalink
Browse files

Templates being cached on init.

  • Loading branch information...
1 parent 7dcf847 commit 36bacddcd6fe0af90aa42025196e9faf0fa4a725 @twentyrogersc committed May 17, 2012
Showing with 25 additions and 20 deletions.
  1. +25 −20 index.js
View
@@ -2,14 +2,16 @@ var crossroads = require('crossroads')
var ejs = require('ejs')
var formidable = require('formidable')
var static = require('node-static')
+var wrench = require('wrench')
var fs = require('fs')
var http = require('http')
+var path = require('path')
var qs = require('querystring')
var url = require('url')
var app = {}
-var settings = {}
+var cache = {}
var routes = {
get: crossroads.create(),
post: crossroads.create()
@@ -18,12 +20,7 @@ var routes = {
app.settings = function(opts) {
for (var opt in opts) {
- switch(opt) {
- case 'template':
- case 'static':
- add[opt](opts[opt])
- break
- }
+ if (opt in add) add[opt](opts[opt])
}
return app
}
@@ -38,32 +35,40 @@ var add = {
regex = new RegExp(regex)
var staticCb = function(req, res) {
- var path = req.url.pathname.match(regex)[1]
+ var f = req.url.pathname.match(regex)[1]
req.addListener('end', function() {
- file.serveFile(path, 200, {}, req, res)
+ file.serveFile(f, 200, {}, req, res)
})
}
routes.get.addRoute(regex, staticCb, 1)
routes.post.addRoute(regex, staticCb, 1)
},
template: function(opts) {
- settings.template = opts.dir
+ var files = wrench.readdirSyncRecursive(opts.dir)
+ files.forEach(function(file) {
+ var p = path.join(opts.dir, file)
+ var stats = fs.statSync(p)
+ if ( stats.isDirectory() === false ) {
+ var template = fs.readFileSync(p)
+ cache[file] = template.toString()
+ }
+ })
}
}
var render = function(template, data, code) {
- var res = this
- template = [settings.template, template].join('/')
- fs.readFile(template, function (err, buff) {
- if (err) throw err
- var html = ejs.render(buff.toString(), data)
- code = code === undefined ? 200 : code
- var head = { 'Content-Type': 'text/html' }
- res.writeHead(code, head)
- res.end(html)
- })
+ if (template in cache === false) {
+ throw new Error('template does not exist')
+ return
+ }
+
+ var html = ejs.render(cache[template], data)
+ code = code === undefined ? 200 : code
+ var head = { 'Content-Type': 'text/html' }
+ this.writeHead(code, head)
+ this.end(html)
}
var json = function(obj, code) {

0 comments on commit 36bacdd

Please sign in to comment.