DEV Community

loading...
Cover image for Day 39 of #100DaysOfCode: Two ways to generate the HTML file in Node.js Express

Day 39 of #100DaysOfCode: Two ways to generate the HTML file in Node.js Express

jenhsuan profile image Jen-Hsuan Hsieh ・2 min read

Introduction

To generate the report of the collected information, I used the Razor engine to generate a HTML file in the C# program.

However, I have to refactor this program and rewrite it as the web version. I decide to generate it on the server-side.

There are two choices I found for generating the HTML file in Node.js.

1.html-creator

I thought that it's convenient to use in the front-end side or Node.js. However, it seems that I can't use embedded CSS in the HTML file.

2.EJS

EJS is a simple template language to generate HTML markup. It allow us to generate high customized HTML file. I use this way for my task and there are a few steps to use EJS to generate the HTML file.

Step 1. Install packages

npm install -s ejs express
Enter fullscreen mode Exit fullscreen mode

Step 2. Modify the node.js entry file (index.js)

const fs = require('fs');
const ejs = require("ejs");
const express = require('express');
const router = express.Router();

...
router.post('/api/example', async function (req, res) {
   const {name, items} = req.body.params;
    const destFolder = 'reports';
   generateHtmlFromEjs(__dirname, destFolder, 'report,html' '/templates/report.ejs', information)
   res.send('complete');
}
...

const generateHtmlFromEjs = (basePath, destFolder, name, template, information) => {
  fs.readFile(path.join(basePath, template), 'utf8', function (err, data) {
      if (err) { 
          console.log(err); 
          return false; 
      }
      const ejsString = data;
      const template = ejs.compile(ejsString);
      const html = template(information);
      fs.writeFile(path.join(basePath, destFolder, name), html, function(err) {
          if(err) { 
            console.log(err); 
            return false; 
          }

          return true;
      });  
  });
};

Enter fullscreen mode Exit fullscreen mode

Step 3. Create the template file (/templates/report.ejs)

  • <%= %> is to show variables passed from ejs.compile
  • <% %> is to write JavaScript logics
  • Example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%= name %></title>
</head>
<body>
    <ol>
    <% for(var i=0; i < items.length; i++) { %>
        <li>
            <p><%= items[i].desciption=></p>
        </li>
    <% } %>
    </ol>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 4. Launch the server

node index.js
Enter fullscreen mode Exit fullscreen mode

Step 5. Post a request to /api/example with the body

  • The structure of body looks like the following example
{
    name: 'example'
    items: [
    {
         description: 'hello',
        ...
    },
    ...]
}
Enter fullscreen mode Exit fullscreen mode

References

Articles

There are some of my articles. Feel free to check if you like!

Discussion (0)

pic
Editor guide