2

I'm using Node.js for an automation work, I have JSON data and I want to generate html files from them after every interval. For example, I have a function which retrieves all the JSON data from database and now I want it to automatically generate .html files to a path from the given JSON data. How can I approach this ? Is there any node library or any examples to do it ? This is my json:

[
 {
    id: '5ffee71aef57d4cf197729a5',
    date_checked: '2021-02-11T07:56:39.042Z',
    title: 'Notification with API',
    status: 'created',
    reach: null,
    sent: null,
    delivered: null,
    views: null,
    clicks: null,
    unsubscribers: null
  },
  {
    id: '5ffee71aef57d4cf197729a5',
    date_checked: '2021-02-11T07:56:39.042Z',
    title: 'Notification with API',
    status: 'created',
    reach: null,
    sent: null,
    delivered: null,
    views: null,
    clicks: null,
    unsubscribers: null
  }
]

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35

2 Answers2

3

This script creates simple html for your json You can expand the columns array to add additional fields that you want to be in your table.

const fs = require('fs')
const columns = [];
for (let name in json[0]){
  if(!json[0].hasOwnProperty(name)) continue;
  columns.push(name);
}

const html = '<html><body><table><thead><tr>';

for (let item of columns) {
  html += '<th>' + item + '</th>';
}

html += '</tr></thead><tbody>';

for (let item of json) {
  html += '<tr>';
  for (let name of columns) {
    html += '<td>' + item[name] +'</td>';
  }
  html += '</tr>';
}

html += '</tbody></table></body></html>';
fs.writeFileSync(new Date().getTime().toString() + '.html', html);
Dilek
  • 83
  • 8
Mike Malyi
  • 983
  • 8
  • 18
-1

I created a sample html model for generating html files.

htmlkit.ts

const { isUndefined } = require("lodash");

module.exports = class HTMLKit {

    data = [];
    curr_x = 0;
    curr_y = 0;
    fontSize = 'medium';

    constructor() { }

    x_pos = (spaces) => {
        this.data.push('&nbsp;'.repeat(spaces));
        this.curr_x = spaces;
    }
    y_pos = (lines) => {
        this.data.push('<div></div>'.repeat(lines));
        this.curr_y = lines;
    }
    text = (t_data, spaces, lines, fontSize = null) => {
        this.data.push(t_data);
    }
    td = (t_data, t_class = "") => {
        this.data.push(`<td class='${t_class}'>${t_data}</td>`)
    }
    tr = (action) => {
        this.data.push((action == 'start') ? '<tr>' : '</tr>');
    }
    tbl = (action, def = [], tbl_class) => {
        var thString = ``;
        def.forEach(th => {
            thString += `<th class='${th}'></th>`
        });
        this.data.push((action == 'start') ? `<table class='${tbl_class}'>${thString}` : '</table>');
    }
    wrap = (action, w_class) => {
        this.data.push((action == 'start') ? `<div class='${w_class}'>` : `</div>`)
    }
    setGlobFontSize = (font_size_index) => {
        const fontSizeArr = ['small', 'medium', 'large']
        this.fontSize = fontSizeArr[font_size_index];
    }
    getGlobFontSize = () => {
        return `<style>html, body, div, span{font-size: ${this.fontSize} !IMPORTANT;}</style>`;
    }
}
html.generator.js
const doc = new DOC();
const styles = STYLES.tr_styles;

doc.text(`<html>${styles}<body>`)
        data.forEach(el => {
            var p_mode = getPaymentMode(el.paymentmode);
            var t_type = getTransType(el.transtype);

            doc.setGlobFontSize(0)
            doc.wrap('start', 'container')
            doc.tbl('start', ["col-1", "col-2", "col-3"], 'tbl-class')
            doc.tr('start')
            doc.td('some data here')
            doc.tr('end')
            doc.tbl('end')
            doc.wrap('close', 'container')
        });
        doc.text(`</body></html>`)
        textData = doc.data.join('');

        fs.writeFileSync(f_name, textData, (err) => {
            if (err) throw err;
            // console.log('HTML Generated')
        });
        return { "status": true, "error": "OK" };
html.models.js
module.exports.fd_styles = `<style type="text/css"> @page{size:8in 6in;margin:0}body{font-size:small;margin:0;padding:0}div.container{width:21cm;height:15.24cm;padding:0}table{column-gap:10px;padding:0 45px 0 60px;width:100%;font-size:small}th.dummy-8{width:8%}th.dummy-10{width:10%}th.dummy-20{width:20%}th.dummy-15{width:15%}th.dummy-0-5{width:20%}th.dummy-25{width:25%}th.dummy-30{width:30%}td{height:25px}thead{height:0}.details{position:relative;top:calc(70px + 20px)}.details-1{position:relative;top:calc(70px + 20px)}.details-2{position:relative;top:calc(70px + 15px)}.details-3{position:relative;top:calc(70px + 10px)}.details-4{position:relative;top:calc(70px)}.details-5{position:relative;top:calc(70px + 10px)}.details-6{position:relative;top:calc(70px + 15px)}.center{text-align:center} </style>`;
Srinath Kamath
  • 542
  • 1
  • 6
  • 17
  • i didn't understood, can you share any repo reference or the structure – prashant padadune Feb 11 '21 at 11:51
  • @prashantpadadune, I have made a model aka a class to handle the html tag insertions for a genric use. You can refer the ```html.generator.js``` to initialise the instance of the class and then use the ```doc``` object of the htmlkit class to create wrappers, tables or htm elements. – Srinath Kamath Feb 12 '21 at 05:43