user3658423
user3658423

Reputation: 1944

node.js/Jade - How to pre-compile jade files and cache it?

Framework: node.js / express.js / Jade

Question: in production env, when a jade file is rendered by express, jade cache's it so future renders are faster.

When I start node.js app, how can I pre-compile (or) pre-render (like warmup) all the jade files so its already in cache when requests start to come in...

I can use a folder recursion, I just need to know how to pre-compile (or) pre-render.

Is this possible?

Upvotes: 9

Views: 4552

Answers (3)

Behnam
Behnam

Reputation: 6459

i do this solution, this code outside http.createServer function

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

and when return view

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

when use this solution server return index to 1ms but without solution server return index between 150ms to 400ms

result:

Picture 1 with cache enter image description here

Picture 2 without cache enter image description here

Upvotes: 0

Rivenfall
Rivenfall

Reputation: 1263

If you're not using any parameters, you can compile jade templates directly to HTML with grunt or gulp and make it watch for file modifications

Try it from the command-line: jade view/map-beacons.jade -D

If you do need to use parameters I would use something like in Andrew Lavers answer.

compileFile returns a function which you can use to pass in parameters i.e. fn({ myJsVar: 'someValue' })

There is also a client option in the command-line but I didn't find any use for it : jade view/map-beacons.jade -cD

Upvotes: 1

Andrew Lavers
Andrew Lavers

Reputation: 8141

Jade has template pre-compiling and caching built in.

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

Simply specify cache: true option to jade.compileFile, and iterate through all of your template files.

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');

Upvotes: 6

Related Questions