node.js/Jade - 如何预编译 jade 文件并缓存它?
node.js/Jade - How to pre-compile jade files and cache it?
框架:node.js/express.js/玉
问题:在生产环境中,当一个 jade 文件被 express 渲染时,jade 缓存了它,所以以后的渲染速度会更快。
当我启动 node.js 应用程序时,我如何预编译(或)预渲染(如预热)所有 jade 文件,以便在请求开始进入时它已经在缓存中...
我可以使用文件夹递归,我只需要知道如何预编译(或)预渲染。
这可能吗?
Jade 内置模板预编译和缓存。
只需将 cache: true
选项指定给 jade.compileFile
,然后遍历所有模板文件。
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');
如果您不使用任何参数,您可以使用 grunt 或 gulp 将 jade 模板直接编译为 HTML 并使其监视文件修改
从命令行试试:
jade view/map-beacons.jade -D
如果您确实需要使用参数,我会使用类似于 Andrew Lavers 回答中的内容。
compileFile
returns 一个可以用来传入参数的函数,即 fn({ myJsVar: 'someValue' })
命令行中还有一个客户端选项,但我没有发现它有任何用处:
jade view/map-beacons.jade -cD
我做这个解决方案,这段代码在 http.createServer 函数之外
let cache_index=jade.renderFile('index.jade');
并且当 return 查看
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(cache_index);
使用此解决方案时服务器 return 索引为 1 毫秒
但没有解决方案服务器 return 索引在 150 毫秒到 400 毫秒之间
结果:
带缓存的图片1
图2无缓存
框架:node.js/express.js/玉
问题:在生产环境中,当一个 jade 文件被 express 渲染时,jade 缓存了它,所以以后的渲染速度会更快。
当我启动 node.js 应用程序时,我如何预编译(或)预渲染(如预热)所有 jade 文件,以便在请求开始进入时它已经在缓存中...
我可以使用文件夹递归,我只需要知道如何预编译(或)预渲染。
这可能吗?
Jade 内置模板预编译和缓存。
只需将 cache: true
选项指定给 jade.compileFile
,然后遍历所有模板文件。
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');
如果您不使用任何参数,您可以使用 grunt 或 gulp 将 jade 模板直接编译为 HTML 并使其监视文件修改
从命令行试试:
jade view/map-beacons.jade -D
如果您确实需要使用参数,我会使用类似于 Andrew Lavers 回答中的内容。
compileFile
returns 一个可以用来传入参数的函数,即 fn({ myJsVar: 'someValue' })
命令行中还有一个客户端选项,但我没有发现它有任何用处:
jade view/map-beacons.jade -cD
我做这个解决方案,这段代码在 http.createServer 函数之外
let cache_index=jade.renderFile('index.jade');
并且当 return 查看
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(cache_index);
使用此解决方案时服务器 return 索引为 1 毫秒 但没有解决方案服务器 return 索引在 150 毫秒到 400 毫秒之间
结果:
带缓存的图片1
图2无缓存