node.js / Jade – 如何预先编译jade文件并caching它?

框架:node.js / express.js / Jade

问题:在生产env中,当一个jade文件被快速渲染时,jade的caching会使未来的渲染速度更快。

当我启动node.js应用程序时,我怎么能预先编译(或)预渲染(如热身)所有的玉文件,所以它已经在caching中,当请求开始进入…

我可以使用文件夹recursion,我只需要知道如何预编译(或)预渲染。

这可能吗?

Jade内置了模板预编译和caching。

http://jade-lang.com/api/

只需指定jade.compileFile cache: true选项,并遍历所有模板文件即可。

 var options = {cache: true}; // iterate/recurse over your jade template files and compile them jade.compileFile('./templates/foo.jade', options); // Jade will load the compiled templates from cache (the file path is the key) jade.renderFile('./templates/foo.jade'); 

如果你没有使用任何参数,你可以直接将玉石模板编译成HTML格式,然后让它监视文件的修改

从命令行试试: jade view/map-beacons.jade -D

如果你确实需要使用参数,我会用Andrew Lavers的答案。

compileFile返回一个函数,你可以用它来传递参数,例如fn({ myJsVar: 'someValue' })

在命令行中还有一个客户端选项,但是我没有发现它的用处: jade view/map-beacons.jade -cD

我做这个解决scheme,这个代码在http.createServer之外

 let cache_index=jade.renderFile('index.jade'); 

和什么时候返回视图

 res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end(cache_index); 

当使用此解决scheme服务器返回索引到1ms但没有解决scheme服务器返回索引150ms到400ms之间

结果:

图片1与caching 在这里输入图像描述

图片2没有caching 在这里输入图像描述