Created
June 25, 2012 16:02
-
-
Save Satyam/2989468 to your computer and use it in GitHub Desktop.
template server
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 express = require('express'), | |
fs = require('fs'), | |
path = require('path'), | |
server = express.createServer(), | |
rexpTEMPLATE = /TEMPLATES\s*=\s*\{\s*\}/, | |
rexpJs = /\.js$/i, | |
rexpHtml = /\.html$/i, | |
VIEWS = '/scripts/views/', | |
MODELS = '/scripts/models/'; | |
server.use(MODELS, express.static(path.join(__dirname , MODELS))); | |
server.get(VIEWS + ':name', function (req, res) { | |
var fileName = req.param('name'), | |
templates = {}; | |
fs.readFile(path.join(__dirname,VIEWS,fileName), 'utf8', function (err, view) { | |
if (err) throw err; | |
var templateDir = path.join(__dirname,VIEWS,fileName.replace(rexpJs,'.templates')); | |
fs.readdir(templateDir, function (err, templateNames) { | |
if (err) throw err; | |
var n = templateNames.length; | |
templateNames.forEach(function(templateName) { | |
fs.readFile(path.join(templateDir , templateName), 'utf8', function(err, template) { | |
if (err) throw err; | |
templates[templateName.replace(rexpHtml,'')] = template; | |
n -= 1; | |
if (!n) { | |
res.send(view.replace(rexpTEMPLATE, 'TEMPLATES = ' + JSON.stringify(templates))); | |
} | |
}); | |
},this); | |
}); | |
}); | |
}); | |
server.get('/', function (req, res) { | |
res.sendfile('index.html'); | |
}); | |
server.get('*', function (req, res) { | |
res.redirect('/#' + req.url, 302); | |
}); | |
server.listen(process.env.PORT || 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This revision of the code assumes the templates for a particular view will be stored in a folder with the same name as the view (without the .js extension) with a .templates extension added. Then, it will add any file it finds there to the TEMPLATES object on the view using the name of each .html file, without the extension.
Another improvement on the previous version is that it primes the loading of the templates all in parallel. In the previous version it did one at a time. Here, it does all the calls to readFile for all the templates all at once and it can accept them in any order they might return.