简体   繁体   English

使用nodejs从json生成.html文件

[英]Generate .html files from json using nodejs

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.我正在使用 Node.js 进行自动化工作,我有 JSON 数据,我想在每个间隔后从它们生成 html 文件。 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. 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:这是我的 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
  }
]

This scripts creates simple html for you json You can expand columns array to add additional fields that you want to be in your table.此脚本为您创建简单的 html json 您可以展开列数组以添加您希望在表中的其他字段。

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>';
file.writeFileSync(new Date().getTime().toString() + '.html', html);

I created a sample html model for generating html files.我创建了一个示例 html model 用于生成 html 文件。

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>`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM