template_server.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. var Promise = require('bluebird');
  2. var async = require('async');
  3. var fs = require('fs');
  4. var crypto = require('crypto');
  5. var Path = require('path');
  6. var HB = require('handlebars');
  7. var express = require('express');
  8. var route = express.Router();
  9. var tempFilter= new RegExp('\.html$', 'i');
  10. var templates = {};
  11. function refresh() {
  12. var tmps = {};
  13. listDir('./templates', tmps);
  14. templates = tmps;
  15. }
  16. function sanitizePath(p) {
  17. return p.replace(/^\/?templates?\/?/i, '').replace(/\.html?$/i, '');
  18. }
  19. function listDir(path, out) {
  20. return fs.readdirSync(path).map(function(filename) {
  21. var p = Path.join(path, filename);
  22. var s = fs.statSync(p);
  23. if(s.isDirectory()) {
  24. listDir(p, out);
  25. }
  26. if(s.isFile() && tempFilter.test(filename)) {
  27. out[sanitizePath(p)] = loadTemplate(p);
  28. }
  29. })
  30. }
  31. function loadTemplate(p) {
  32. var src = fs.readFileSync(p, 'utf-8');
  33. return {
  34. hash: crypto.createHash('sha1').update(src).digest('hex'),
  35. filepath: sanitizePath(p),
  36. source: src,
  37. template: HB.precompile(src),
  38. };
  39. }
  40. refresh();
  41. route.all('/fetch', function(req, res) {
  42. res.send(JSON.stringify(templates[req.params.name]));
  43. });
  44. route.all('/all', function(req, res) {
  45. res.send(JSON.stringify(templates));
  46. });
  47. route.all('/tree/*', function(req, res) {
  48. });
  49. module.exports = {
  50. router: route,
  51. refresh: refresh,
  52. };