S
S
Stopy2015-08-20 21:46:11
Node.js
Stopy, 2015-08-20 21:46:11

How to render templates?


A common case is when a template is rendered in express.js using the res.render('template', args) method, but recently I ran into this method:

var templatePath = require.resolve('../views/view.jade');
var templateFn = require('jade').compileFile(templatePath);

and then use
res.write(templateFn(args));
res.end();

Moreover, the rendering speed using res.render () is on average from 50 to 25 ms, and in the second way from 23 to 7 ms.
What is the difference and why is one 3 times faster than the second?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Prozorov, 2015-08-20
@Stopy

The rendering speed may differ because in the first case, express is not running in production mode, and does not cache templates, each time reading them from disk for each request. This is where the overhead comes from. Those. when you change the template on disk, you do not need to restart the process to see changes in the response of the service - this is convenient for development, but naturally works slower.
In your example of the second way, the template is cached in process memory in templateFn(). Those. when you change the template on disk, nothing will change in your output until you restart the application process. In fact, the production mode is implemented immediately.
Try running an express application with the "normal" way of rendering by setting an environment variable
and compare the speed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question