parse.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var fs = require('fs');
  2. var ejs = require('ejs');
  3. var EventProxy = require('eventproxy');
  4. var ep = new EventProxy();
  5. // 在所有指定的事件触发后,将会被调用执行
  6. // 参数对应各自的事件名的最新数据
  7. ep.tail('basehead', 'head', 'nav','leftbar', 'foot', 'basefoot', 'main', function(basehead,
  8. head, nav, leftbar, foot, basefoot, mainArr) {
  9. render(basehead, head, nav, leftbar, foot, basefoot, mainArr[0], mainArr[1]);
  10. });
  11. // 读取Base头部模板
  12. fs.readFile('../unitTpl/basehead.html.tpl', 'utf8', function(err, basehead) {
  13. if (err)
  14. throw err;
  15. ep.emit('basehead', basehead);
  16. });
  17. // 读取头部模板
  18. fs.readFile('../unitTpl/head.html.tpl', 'utf8', function(err, head) {
  19. if (err)
  20. throw err;
  21. ep.emit('head', head);
  22. });
  23. // 读取导航模板
  24. fs.readFile('../unitTpl/nav.html.tpl', 'utf8', function(err, nav) {
  25. if (err)
  26. throw err;
  27. ep.emit('nav', nav);
  28. });
  29. //读取左侧导航模板
  30. fs.readFile('../unitTpl/leftbar.html.tpl', 'utf8', function(err, leftbar) {
  31. if (err)
  32. throw err;
  33. ep.emit('leftbar', leftbar);
  34. });
  35. // 读取尾部模板
  36. fs.readFile('../unitTpl/foot.html.tpl', 'utf8', function(err, foot) {
  37. if (err)
  38. throw err;
  39. ep.emit('foot', foot);
  40. });
  41. // 读取尾部模板
  42. fs.readFile('../unitTpl/basefoot.html.tpl', 'utf8', function(err, basefoot) {
  43. if (err)
  44. throw err;
  45. ep.emit('basefoot', basefoot);
  46. });
  47. // 读取页面主模板
  48. fs.readdir("../mainTpl", function(err, dirArr) {
  49. if (err)
  50. throw err;
  51. dirArr.forEach(function(item, index) {
  52. var name = /^(\w+)\.tpl/.exec(item)[1];
  53. var mainPath = "../mainTpl/" + item;
  54. fs.readFile(mainPath, 'utf8', function(err1, main) {
  55. if (err1)
  56. throw err1;
  57. ep.emit('main', [ main, name ]);
  58. });
  59. });
  60. });
  61. // 转义html标签
  62. function decodeHtml(html) {
  63. return String(html).replace(/&/g, "&").replace(/"/g, '"').replace(
  64. /&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
  65. }
  66. // 拼接模板
  67. function render(basehead, head, nav, leftbar, foot, basefoot, main, name) {
  68. var html = ejs.render(main, {
  69. "page" : {
  70. "basehead" : basehead,
  71. "head" : head,
  72. "nav" : nav,
  73. "leftbar":leftbar,
  74. "foot" : foot,
  75. "basefoot" : basefoot
  76. }
  77. });
  78. var html = decodeHtml(html);
  79. createFile(html, name);
  80. }
  81. // 生成最终文件
  82. function createFile(html, name) {
  83. fs.writeFile('../' + name + '.html', html, 'utf8', function(err) {
  84. if (err)
  85. throw err;
  86. console.log(name + '.html is created!'); // 文件被保存
  87. });
  88. }