Home > Software design >  Generate HTML files through Express/EJS/FS and serve them through Nginx instead of express
Generate HTML files through Express/EJS/FS and serve them through Nginx instead of express

Time:01-20

Let's say we have a JSON:

[
  {
    "id": 1,
    "title": "Title 1",
    "description": "Description 1"
  },
  {
    "id": 2,
    "title": "Title 2",
    "description": "Description 2"
  },
  {
    "id": 3,
    "title": "Title 3",
    "description": "Description 3"
  }
]

And an EJS file called index.ejs

<!DOCTYPE html>
<html lang="en">
  <body>
    <% data.forEach(item => { %>
    <h1><%- item.title %></h1>
    <p><%- item.description %></p>
    <% }) %>
  </body>
</html>

I can simply use this javascript code to render the data through express:

const express = require("express");
const app = express();

const data = require("./data.json");

app.set("view engine", "ejs");

app.get("/", (req, res) => {
  res.render("index", { data });
});

app.listen(4000);

However, what if I want to create the 3 HTML pages instead and serve them through Nginx? I could use fs to create the html files. But the question is, how can I create the 3 generated pages using EJS but render the pages through Nginx instead of node.js's app.get()?

CodePudding user response:

If the data is static (it's known in advance and doesn't change), you can generate the HTML pages once as part of some build process by writing a separate nodejs script that uses EJS to generate the HTML files and then save the generated HTML files to an nginx specific directory and let nginx serve the static web pages from there.

I've done something similar for a github.io web-site where I used a nodejs script and a template engine to pre-generate static HTML pages which were then served through github.io. This allowed me to use the features of templates (common header, common footer, common styles, etc...) to generate a set of static HTML pages. When I want to update the web pages, I can just update the templates and regenerate rather than manually editing every single HTML page.

If the data is dynamic, then nginx has no idea how to generate them as it doesn't directly support these types of template engines (which are designed for Javascript engines) so you would stick with serving EJS templates from nodejs.

  •  Tags:  
  • Related