Day 39 of #100DaysOfCode: Two ways to generate the HTML file in Node.js Express
Tags: node, javascript, 100daysofcode, webdev
Published: 2020-10-27 12:04:46

## Introduction
To generate the report of the collected information, I used the [Razor engine](https://medium.com/a-layman/refactor-your-html-report-with-razorengine-59e878ac9d52) 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](https://github.com/Hargne/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](https://ejs.co/)
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
```

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

```javascript
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;
      });  
  });
};

```

### Step 3. Create the template file (/templates/report.ejs)
* <%= %> is to show variables passed from ```ejs.compile```
* <% %> is to write JavaScript logics
* Example

```html
<!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>
```

### Step 4. Launch the server
```
node index.js
```

### 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',
        ...
    },
    ...]
}
```

## References
* [Generate static HTML files from ejs templates](https://stackoverflow.com/questions/30976477/generate-static-html-files-from-ejs-templates)

## Articles
There are some of my articles. Feel free to check if you like! 
* My blog-posts for software developing: https://medium.com/a-layman
* My web resume: https://jenhsuan.github.io/ALayman/cover.html
* Facebook page: https://www.facebook.com/imalayman
* Twitter bot: https://twitter.com/ALayman84368087