UNPKG

@alinex/datastore

Version:

Read, work and write data structures from and to differents locations and formats.

85 lines 2.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.format = exports.parse = void 0; const path_1 = require("path"); const debug_1 = require("debug"); const htmlparser2_1 = require("htmlparser2"); const domhandler_1 = require("domhandler"); const util_1 = require("util"); const debug = debug_1.default('datastore:format:html'); function dom2array(dom) { return dom.map(e => { switch (e.type) { case 'directive': return { '!': e.data }; case 'text': return { _: e.data }; case 'tag': let content = []; if (Object.keys(e.attribs).length) content.push({ $: e.attribs }); if (e.children) content = content.concat(dom2array(e.children)); const data = {}; data[e.name] = content; return data; default: console.log('missing: ' + util_1.inspect(e, { depth: 0 })); return e; } }); } function array2html(data) { return data .map(e => { if (e['!']) return `<${e['!']}>`; if (e['_']) return e['_']; if (e['$']) return ''; const tag = Object.keys(e)[0]; const attrib = array2attrib(e[tag]); if (Object.keys(e[tag]).filter(s => s !== '$').length) return `<${tag}${attrib}>` + array2html(e[tag]) + `</${tag}>`; return `<${tag}${attrib}/>`; }) .join(''); } function array2attrib(data) { const att = data.filter(e => Object.keys(e).filter(n => n == '$').length); if (!att.length) return ''; return Object.keys(att[0]['$']) .map((e) => ` ${e}="${att[0]['$'][e]}"`) .join(''); } const parse = async function (parsedUri, buffer) { if (!parsedUri.pathname) return Promise.reject(`No pathname given in ${parsedUri.href}`); const pathname = parsedUri.hash || path_1.basename(parsedUri.pathname); debug(`parsing ${pathname}`); let data; const handler = new domhandler_1.DomHandler(function (error, dom) { if (error) { const e = new Error('Could not parse html: ' + error); e.data = buffer.toString(); return Promise.reject(e); } data = dom2array(dom); }); const parser = new htmlparser2_1.Parser(handler); parser.write(buffer.toString()); parser.end(); return data; }; exports.parse = parse; const format = function (parsedUri, data, options) { if (!parsedUri.pathname) return Promise.reject(`No pathname given in ${parsedUri.href}`); const pathname = parsedUri.hash || path_1.basename(parsedUri.pathname); debug(`formatting for ${pathname}`); return Promise.resolve(Buffer.from(array2html(data))); }; exports.format = format; //# sourceMappingURL=html.js.map