【问题标题】:How to save rendered html view files from ExpressJS Routes如何从 ExpressJS 路由中保存呈现的 html 视图文件
【发布时间】:2020-06-15 01:54:58
【问题描述】:

我已经使用ExpressJSPUG 构建了几个静态网站页面,以获得模板引擎的优势。

但现在我需要导出所有 ExpressJS Routes 正在呈现的所有原始 HTML。

是否有任何软件包可以帮助我做到这一点?或者我必须编写自定义命令并遍历所有 Routes 并保存呈现的输出?

如果自定义命令是唯一的方法,我如何遍历所有 routes 并获得渲染输出?

【问题讨论】:

标签: html node.js express pug


【解决方案1】:

我找不到任何库或资源来实现我想要的。但是通过我的一些脏代码、hack 和包,我能够导出所有路由。

注意:我没有写一个节点命令来导出html,而是添加了一个路由来触发操作这里是路由的代码:

app.use('/export_templates', router.get('/', async function (req, res, next) {
  const endpoints = listEndpoints(app);
  const failedEndpoints = [];

  for (const i in endpoints) {
    const endpoint = endpoints[i];

    if (endpoint.path == '/export_templates') {
      continue;
    }

    try {
      const res = await axios.get('http://'+req.headers.host+''+endpoint.path+'?export=true');
    }
    catch(error) {
      failedEndpoints.push(endpoint.path);
    }
  }

  res.json({
    "status": "succes",
    "message": "Please check templates folder for the latest exported html templates",
    "failed": failedEndpoints
  })
}));

基本上这个路由迭代并使用export=true参数向所有可用路由发出请求。

然后在每个路由视图函数中,一个条件检查导出参数是否可用,然后调用 exportTemplateFile 函数,并将 pug 模板位置和新文件名作为函数参数。 如果请求不包含export 参数,则请求的路由将简单地输出什么模板。

示例路线:

router.get('/', function(req, res, next) {
  if (req.query.export) {
    exportTemplateFile('views/index.pug', 'index.html');
  }

  res.render('index.pug');
});

这是完成导出过程的2个util函数的代码

function createTemplateFile(filename) {
  fs.open(filename,'r',function(err, fd){
    if (err) {
      fs.writeFile(filename, '', function(err) {
          if(err) {
              console.log(err);
          }
      });
    }
  });
}

function exportTemplateFile(templateLocation, templateName) {
  const html = pretty(pug.renderFile(templateLocation));

  createTemplateFile('templates/'+templateName);

  var stream = fs.createWriteStream('templates/'+templateName);
  stream.once('open', function (fd) {
    stream.write(html);
    stream.end();
  });
}

createTemplateFile 函数只是在新文件不存在时创建一个新文件。

exportTemplateFile 函数将 HTML 保存在由pug 呈现的html 变量中,并使用pretty 包对其进行美化,然后覆盖新的模板文件。

注意:在我的例子中,所有pug 模板都是静态的,因此我不必将任何上下文传递给pug.renderFile 函数。但是,如果您需要在 pug 模板中使用任何上下文,您可以简单地将其与模板位置一起传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2017-07-31
    • 2013-05-13
    相关资源
    最近更新 更多