/* POR ALGUNA RAZÓN NO ESTÁ GENERANDO BIEN EL ARCHIVO CUANDO SE INVOCA DESDE ACÁ: POR ESO MEJOR SEGUÍ USANDO HANDLEBARS */ /** Función que genera los archivos de acuerdo a una plantilla y a unos datos @param templateFileName Nombre del archivo de plantilla @param destFile Nombre del archivo de salida @para variables Objeto con las variables **/ function renderFile( templateFileName, destFile, datos){ //var datos = JSON.parse(fs.readFileSync(datosFileName , 'utf8')); try{ debugger; var datos = JSON.parse(fs.readFileSync('datos.json', 'utf8')); //var cosa = global.__dirname; //TODO: QUITAR LA CACHE mu.clearCache(); //var currentPath = './'; var currentPath = 'C:/Users/dmonto20/Documents/GitHub/fabrica-Software-JSF-Node/'; mu.root = currentPath; var stream = mu.compileAndRender('./'+templateFileName , datos ); var writable = fs.createWriteStream( destFile ); /*var path = require('path'); var execPath = path.dirname( process.execPath ); console.log(execPath);*/ stream.pipe(writable); }catch( e ) { console.log(e); } }
fs.readFile(filePath, function (err, content) { if (err) { // Cannot read the file. Exit. console.error('Cannot read file '+filePath+': '+err); return errorPage(res, err); } // In dev mode, clear cache immediately. if (!options.cache) { mu.clearCache(pageTemplate); } // Compute summary. makeSummary(function(err, pages) { if (err) { // Cannot read the file. Exit. console.error('Cannot read folder '+options.root+': '+err); return errorPage(res, err); } // Parse the page mustache template. var mapPage = function(val) { return { url: val, name: getName(val) }; }; var tmpl = mu.compileAndRender(pageTemplate, { // Insert inside the page the interpreted markdown content. title: options.title, content: md(content.toString()), pages: pages.map(mapPage) }); util.pump(tmpl, res); }); });
search(searched, function(err, results) { if (err) { console.error('Cannot perform search of '+ searched +': '+err); return errorPage(res, err); } // In dev mode, clear cache immediately. if (!options.cache) { mu.clearCache(searchTemplate); } // Parse the page mustache template. var mapHit = function(value){ return {val:value}; }; var mapResult = function(result) { return { url: result.file, name: getName(result.file), hits: result.hits.map(mapHit) }; }; var tmpl = mu.compileAndRender(searchTemplate, { title: options.title, results: results.map(mapResult), searched: searched }); util.pump(tmpl, res); });
// On utilise mu2 https://github.com/raycmorgan/Mu plutôt que // mustache disponible avec consolidate. mustache ne semble // pas gérer le chargement automatique des parials. function mu2proxy(path, options, callback) { mu.root = 'views'; // bric-à-brac pour gérer mon pseudo proxy if(app.get('views') == "../PhotoFlux/views/") { mu.root = app.get('views'); path = path.substr(mu.root.length); } // on recompile les templates à chaque fois durant le development if (app.get('env') == 'development') { debug("clearing mustache cache"); mu.clearCache(); } var stream = mu.compileAndRender(path, options); var html = ""; stream.on('data', function(data) { html += data; }); stream.on('end', function() { callback(null, html); }); stream.on('error', function(err) { callback(err, null); }); }
Generator.compile = function (fn) { var templates = this.getTemplatesSync(); var list = Generator.getDomainList(); var listJSON = JSON.stringify(list); var listSTR = listJSON.substring(1, listJSON.length - 1); mu.clearCache(); this.emit('loaded:list', list); function iter(template, done) { var d = ''; this.emit('compiling:template', template); mu .compileAndRender(template.fullpath, { unanchoredRegexpString: unanchoredRegexpString, list: list, listSTR: listSTR, listJSON: listJSON }) .on('data', function (data) { d += data; }) .on('end', function () { this.emit('writing:template', template); fs.writeFile(template.fullOutputPath, d, done); }.bind(this)) .on('error', function (err) { this.emit('error:template', template, err); done(err); }); } async.eachLimit(templates, 5, iter.bind(this), fn); };
http.createServer( function ( req, res ) { var query = url.parse( req.url, true ).query, types = { 'js': { type: 'js', mimeType: 'application/javascript' }, 'css': { type: 'css', mimeType: 'text/css' } }, size = parseInt( query.size, 10 ) || 200, type = types[ query.type ] ? types[ query.type ].type : 'js', data = new Array( size ).join('.').split('.').map(function ( key, i ) { return { raw: i }; }); mu.clearCache(); var stream = mu.compileAndRender( type + '.mustache', { "data": data }); res.writeHead( 200, { 'Content-Type': type.mimeType }); util.pump(stream, res); }).listen( process.env.PORT );
function renderFile (res, path, options) { // If you need to render a file with a different content // type, do it directly on the response object if (process.env.NODE_ENV !== 'production') { mu.clearCache(); } res.set('Content-Type', 'text/html; charset=utf-8'); mu.compileAndRender(path, options).pipe(res); }
exports.serve = function (options,fn,type,args,res,data) { if((fn.charAt(0) !== '/') && (fn.charAt(1) !== ':')) { fn = options.content + '/' + fn; } if(type.startsWith("text/") || (type === "application/json") || (type === "application/javascript")) { log.info("Processing: " + fn); if(options && options.devMode) { mu.clearCache(options); } var context = data || {}; if(args) { context.args = args; context.params = args.fields; context.files = args.files; } if(options) { context.opts = options; } mu.compileAndRender(fn,context).pipe(res); } else { fs.readFile(fn,function(err,file) { if(!err) { log.debug("Serving: " + fn + " [" + type + ']'); res.writeHead(200,"OK",{"Content-Type": type}); res.end(file); } else { log.error("Error: " + err); res.writeHead(500,"Server Error",{"Content-Type": "text/plain"}); res.end("500 Internal Server Error: " + err); } }); } }; //serve
var html = (function() { mu.clearCache();//clear the cache for mu rendering -- speed up performance! for (var page in data.pages) { mustache_compiler.compile(page, data.pages[page]); } }());
function renderPage(res, template, variables) { var stream = mu.compileAndRender(template, variables); res.header('Content-Type', 'text/html'); if (config.hasOwnProperty("debug") && config.debug) { mu.clearCache(); } stream.pipe(res); }
var compile = function (html, css, text, data, templateName, callback) { // Check if we're going to use a template if (templateName !== '') { html = path.join(config.templateDirectory, templateName, 'index.html'); css = path.join(config.templateDirectory, templateName, 'index.css'); text = path.join(config.templateDirectory, templateName, 'index.txt'); } // Check if we're going to use juice var juiced = false; if (css !== '') juiced = true; // Clear cache if (config.env.toUpperCase() === 'DEVELOPMENT') mustache.clearCache(); // Processor var proc = function (input, data, css, callback) { var abspath = path.resolve(input), buffer = ''; mustache.compileAndRender(abspath, data) .on('error', function (err) { callback(err); }) .on('data', function (data) { buffer += data.toString(); }) .on('end', function () { // Utilize juice to compile HTML with inline CSS styling if (juiced) { fs.readFile(css, 'utf8', function(err, style) { if (err) { callback(err); } else { buffer = juice(buffer, style); callback(null, buffer); } }); } else { callback(null, buffer); } }); }; // Compile & return HTML and text inputs async.auto({ html: function (callback) { proc(html, data, css, callback); }, text: function (callback) { proc(text, data, css, callback); } }, callback); };
app.engine('mustache', function (path, options, fn) { var buffer = []; // Always recompile in development if (app.settings.env === 'development') { mustache.clearCache(); } mustache.compileAndRender(path, options).on('data', function (data) { buffer.push(data); }).on('end', function () { fn(null, buffer.join('')); }).on('error', function (e) { fn(e); }); });
var server = http.createServer(function (request, response) { var handled = false; routes.forEach(function(entry) { var pathname = url.parse(request.url).pathname; if (pathname.match(entry.pattern) != null && request.method == entry.method) { entry.handler(client, emitter, request, response); handled = true; } }); if (!handled) { response.writeHead(404, {'Content-Type': 'text/plain'}); response.end('Not found\n'); } if (config.DEBUG) mustache.clearCache(); });
exports.write = function (res, template, vars, status, headers) { if (status && typeof status == "object") { headers = status; status = null; } if (!headers || typeof headers != "object") headers = {}; if (!headers["Content-Type"]) headers["Content-Type"] = "text/html"; if (!headers["Cache-Control"]) headers["Cache-Control"] = "no-cache"; res.writeHead(status || 200, headers); if (process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase() == "development") { mu.clearCache(); } mu.compileAndRender(template, vars || {}).pipe(res); };
"ORDER BY note_count DESC",[], function(error, results) { if (error) { console.log(error); throw error; } var view = { title: app.get("title"), presentations: results }; if (app.get("env") == "dev") { mu.clearCache(); } var stream = mu.compileAndRender('presentations.html', view); util.pump(stream, res); });
function RenderPage(requestUrl, response) { var dataFile = dataResolver.resolve(requestUrl); if (dataFile.status_code === 200) { console.log(("GET " + requestUrl + " 200").green.bold); if (process.env.NODE_ENV == 'DEVELOPMENT') { mu.clearCache(); } var stream = mu.compileAndRender('authors.html', { name: dataFile.path }); stream.pipe(response); } if (dataFile.status_code === 404) { console.log(("GET " + requestUrl + " 404").red.bold); response.writeHead(404, { 'Content-Type': 'text/html' }); response.end("<html><head></head><body>" + dataFile.path + " not found</body></html>"); } }
db.query("SELECT * FROM presentation WHERE filename = ?",[presentationId], function(error, results) { if (error) { console.log(error); throw error; } var view = { title: app.get("title"), is_available: results.length == 1, presentation: results[0] }; if (app.get("env") == "dev") { mu.clearCache(); } var stream = mu.compileAndRender('presentation.html', view); util.pump(stream, res); });
// Haunted House Logistics Server - template writing functions // node modules var path = require("path"); // required modules var mu = require("mu2"); if (process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase() == "development") { mu.clearCache(); } else { console.log("Using mu cache"); } exports.setTemplateDir = function (dir) { mu.root = dir; }; // writer.write(res, template name, [template vars, [status], [headers]]) exports.write = function (res, template, vars, status, headers) { if (status && typeof status == "object") { headers = status; status = null; } if (!headers || typeof headers != "object") headers = {}; if (!headers["Content-Type"]) headers["Content-Type"] = "text/html"; if (!headers["Cache-Control"]) headers["Cache-Control"] = "no-cache"; res.writeHead(status || 200, headers);
app.use(function(req, res, next) { mu.clearCache(); next(); });
var clearCache = function () { MustacheEngine.clearCache(); };