NodeJS, Express, Nginx and Jade… whats the deal?

2019-08-31 02:36发布

问题:

So I'm currently investigating what technologies/libraries etc to adopt for a new, rather large scale project...

Given my teams knowledge of NodeJS, JavaScript, Express and Jade (now Pug) I/WE would ideally like to adopt these for the new project.

However, the current sticking point is the way in which HTML is being served under Express using route middleware.

We all know that Node/Express does a pretty bad job of serving up static files, which is where Nginx comes in. I can understand and even implement an Nginx config that handles the serving of img/js/css static files but what I'm trying to find out is this...

Can the serving of HTML (generated by Jade/Pug), using Express routes be handed over to Nginx in order to boost performance? Or is it the case that if you're using Express routing, you have to accept that serving of HTML files will be slow?

Got to be honest, I'm not quite sure how all this fits together so am hoping someone can shed a little light on this ;-)

Thanks in advance guys and gals

回答1:

Reasonable recommendations:

  • Serve static files with NGINX, you can configure it to fetch the files directly.
  • Serve dynamic files with NGINX proxied to your express app, and set an adequate cache value.

Can the serving of HTML (generated by Jade/Pug), using Express routes be handed over to Nginx in order to boost performance?

Yes if you cache.

Or is it the case that if you're using Express routing, you have to accept that serving of HTML files will be slow?

Not if you cache.

I hope that helps!



回答2:

Without questioning for more details, I can point out some things i keep in mind when developing on Express:

  • Express "default" rendering done through res.render may not be optimal for a number of reasons. For example, lookup for the template file which is recalculated every request
  • Jade template engine doesn't support streaming

I would suggest, before looking at interventions outside application context (such as Varnish or plain Nginx conf), to try:

  • using a template engine supporting streaming: Marko, Dust, Nunjucks

  • if the app is a single-page, or generally an ajax based one, and you don't need any special SEO setup (although, there are fixes for that too), you may also pre-cache the static html then fill it up on the client (but this is really just a rant).

A good overview comes from Strongloop's blog post