Why should you discard the Express view rendering engine?

Source: Internet
Author: User

A widely used feature of the Nodejs Express framework is its rendering engine. The Express view rendering engine allows the Controller to provide a view name and view model object to Express, and then return some bytes output by the HTTP response stream. Based on the experience gained from providing support for eBay's Nodejs technology stack, we discovered the disadvantages of this method and decided to discard it completely. After doing so, we can see that the page loading speed is improved, the page loading performance is better, and the developer productivity is improved. This article will explain why you should not use the Express view rendering engine and provide a recommended alternative.

Express view rendering engine

Before explaining the shortcomings of the Express view rendering engine, let's take a quick look at its usage. First, you must use the following code to configure your Express app:

App. set ('View', path. join (_ dirname, 'view'); app. set ('View engine ', 'Jade ');

The first line of code tells Express to search for all templates under the views directory, and the second line applies the jade template engine to these templates.

After configuration, you can useRes. render (viewName, viewModel)The code is as follows:

App. get ('/', function (req, res) {res. render ('index', {title: 'hei', message: 'Hello there! '});})

Here, Express maps the View name to the path of the template file, uses the associated template engine to render the template, outputs the result to response, and ends the response.

Poor

This method looks so simple that you never thought it would make a mistake. But in fact, it still has many problems. When something goes wrong, it will affect the performance and maintainability of web programs. We will talk about this below.

Destructive

The mandatory requirements of Express are to set a view directory where all templates are stacked. You can place templates near the Controller or the UI components using these templates. Now you have to put them in a separate top-level Directory. A typical Express-based project has a directory structure similar to the following:

Routes/home. js login. js... Views/home. jade login. jade...

Using the directory structure recommended by Express, you have to split the source code by type rather than special. As a result, closely related files will be separated into different directory trees, which means that if you need to modify a function, you may need to traverse the entire project directory to modify different files. In the subsequent alternatives, I will introduce a healthier and modular directory structure.

Highly coupled with Express

When the Express view rendering engine is used, it means that you are using a feature highly coupled with Express. What if you want to render a template on the client? How do I parse a local template? What if you want to switch to another web framework or do not use the framework? The fact is that the new method of parsing and rendering templates introduced by Express can only be used on the server and only in Express. When constructing an homogeneous (isomorphic) web app, we want to use a more consistent rendering Template method on the server and client.

No Streaming

The Express view rendering engine does not support streaming, which negatively affects the performance of both the client and server. On the server side, when rendering an HTML page template, the entire HTML output is stored in the memory as an ultra-long string. After the entire HTML output is constructed, to output the first byte to the HTML response. This is because all view engines must be implemented using callback. Callback is called only when the entire HTML is rendered. Without streaming to output HTML, we will waste the server's memory and increase the client's waiting for response time.

The benefits of using streaming to transmit responses include:<Head>So that the client can download CSS files on the page faster. To feel the benefits of streaming, you need to use a template engine that supports streaming. In addition, templates that support asynchronous rendering (such as Marko, Dust, and Nunjucks) can even output responses before the View model is constructed, thus bringing more performance improvements.

Centralized configuration

Not all configurations are bad, but unnecessary configurations are definitely bad. If the configuration is not needed in different places of the application, the centralized configuration will cause a conflict. For example, if you need multiple view directories? The sub-apps of Express can solve this problem to some extent, but the best way is to avoid additional configuration.

Solution

Express describes itself as a framework, so it is easy to bypass the Express view rendering engine. This will allow developers to create more flexible, understandable, and high-performance applications. First, you must understand an important concept,ResThe object is actually a writable HTTP response stream (although it has been heavily modified by Express), so you can directly output to the response:

App. get ('/', function (req, res) {res. write ('Hello Frank '); res. end ();});

If you want to render a jade template to an HTTP response, you can do the following:

Var templatePath = require. resolve ('. /template. jade '); var templateFn = require ('Jade '). compileFile (templatePath); app. get ('/', function (req, res) {res. write (templateFn ({name: 'Frank'}); res. end ();});

ComparedRes. render ()It is a little too long, but it is intuitive and flexible.

Note: You may notice that we use require. resolve to obtain the absolute path of the template. This template is put together with our Controller module.

If your template engine supports output to a stream, the code will be simpler. For example, the code of the Marko template engine is as follows:

Var templatePath = require. resolve ('. /template. marko '); var template = require ('marko '). load (templatePath); app. get ('/', function (req, res) {template. render ({name: 'Frank'}, res );});

View parser

If you think your app needs to use A view parser (for example, you need to use different templates for A/B testing or determine the template based on your region ), there is also a very clean solution. The following code assumes a view parser independent of Express. It parses the View template based on the name and context (in this example, the request and the current directory.

Var myViewResolver = require ('My-view-resolver '); app. get ('/', function (req, res) {var template = myViewResolver. resolve ('hello', req, _ dirname); template. render ({name: 'Frank'}, res );});

Using a clear view parser makes the code easier to understand and provides higher flexibility.

Project structure

Now, you are not limited to having only one view directory. Let's take a look at the new project structure:

Pages/home/index. js style.css template. marko login/index. js style.css template. marko

The new project structure allows associated files to be placed in the same directory, and modular development and maintenance projects are now available.

Summary

Although Express is a minimalistic framework, there is no need to use all its features. Sometimes an independent module can do better than it. One of the guiding principles of Nodejs is that "the module should only do one thing and do it well", and I think it would be better for Express to separate features such as view rendering and routing. We have seen that many Core middleware products are separated in Express 4.x, and I think we should proceed further. Maybe we don't need a framework at all. Maybe we only need some modules that work well together.

I hope that you are already clear about the benefits of bypassing Express view rendering. If you want to see a specific example, you can refer to the sample program here. There are more weather examples for your reference.

(Source: StrongLoop Blog, author: Patrick Steele-Idem)

Why should you discard the Express view rendering engine?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.