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
  }
]

10
  • You can simply create a model for the html then write to file using writefilesync as a string. Commented Feb 11, 2021 at 11:37
  • It would be nice if you also describe what type of html do you want. Commented Feb 11, 2021 at 11:40
  • I need some more clarity, what exactly you want to achieve? Is It something related to HTML table for just to prettify your JSON? Commented Feb 11, 2021 at 11:43
  • I have added the code to your answer. Just use ES6 syntax to append data into the html string Commented Feb 11, 2021 at 11:45
  • @SrinathKamath is there any reference or examples to achieve it ? Commented Feb 11, 2021 at 11:45

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

9 Comments

this is awsome, how can i add styles to this also how can i change writeFileSync path to another director
For styles you can add attribute class or style to any tag, for example to table or td
For different directoy use this code file.writeFileSync(path + new Date().getTime().toString() + '.html', html);
The easiest way to add styles is to connect Bootstrap <head> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"></head> Add it between <html> and <body> And then add class here <table class="table">
is there any clean way to do this approach ? this exactly what i want but i want to reuse this @Mike Malyi
|
-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>`;

2 Comments

i didn't understood, can you share any repo reference or the structure
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.