我找不到任何库或资源来实现我想要的。但是通过我的一些脏代码、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 模板中使用任何上下文,您可以简单地将其与模板位置一起传递。