Skip to content

Instantly share code, notes, and snippets.

@mateodelnorte
Created June 11, 2013 19:28
Show Gist options
  • Save mateodelnorte/5759866 to your computer and use it in GitHub Desktop.
Save mateodelnorte/5759866 to your computer and use it in GitHub Desktop.
compiling local jade templates for sharing between server and client
var fs = require('fs'),
jade = require('jade'),
util = require('util');
module.exports = new JadeTemplateExporter();
function JadeTemplateExporter(options){
var opts = options || {},
__path = __dirname + '/../views/templates',
__outputPath = __dirname + '/../public/templates/client_templates.js',
__position = 0;
opts.dir = (options && options.dir) ? options.dir : __path;
opts.recurse = (options && options.recurse) ? options.recurse : true;
if(options && options.express)
opts.express = options.exress;
this.options = opts;
var self = this;
var publish = function publish(){
fs.open(__outputPath, 'w', function(err, fd){
if (err) throw err;
publishDirectory(self.options.dir, fd);
});
};
var publishDirectory = function publishDirectory(path, fd){
fs.readdir(path, function(err, files){
if (err) throw err;
files.forEach(function(file){
var filePath = path + '/' + file.toString();
var stats = fs.statSync(filePath); // sync to enforce no overwriting in output file
if(stats.isDirectory(filePath))
publishDirectory(filePath, fd);
else
publishFile(filePath, fd);
});
});
};
function publishFile(path, fd){
fs.readFile(path, function(err, data){
if (err) throw err;
var options = process.env.NODE_ENV === 'production' ? { client: true, compileDebug: false, filename: path } : { client: true, filename: path };
var name = path.replace(__path + '/', '')
.replace('.jade', '')
.replace(/\//g, '_');
console.log('compiling ' + name);
var funcString = jade.compile(data, options)
.toString()
.replace('anonymous', name);
if(process.env.NODE_ENV === 'production'){
var ast = parser.parse(funcString);
ast = uglify.ast_squeeze(ast);
funcString = uglify.gen_code(ast);
}
var previousPosition = __position;
__position = fs.writeSync(fd, funcString + "\n", __position) + previousPosition;
});
};
return {
publish: publish
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment