Skip to content

Instantly share code, notes, and snippets.

@fillano
Last active August 6, 2020 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fillano/e0c66b1a333f6689d5b7b5b8c3a4adf4 to your computer and use it in GitHub Desktop.
Save fillano/e0c66b1a333f6689d5b7b5b8c3a4adf4 to your computer and use it in GitHub Desktop.
poc to build an object tree then run.
const args = require('minimist')(process.argv.slice(2));
const DOMParser = require('xmldom').DOMParser;
const fs = require('fs');
main(args);
function main(args) {
if(args._.length > 0) {
read(args._[0])
.then(body => {
console.log('readed');
let doc = new DOMParser().parseFromString(body);
let root = new Node(null, doc.nodeType, doc.tagName, doc.attributes, doc.nodeValue, doc.childNodes, 0);
root.run();
}, reason => {
console.log(reason);
help();
})
} else {
help();
}
}
function read(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if(!!err) return reject(err.message);
resolve(data);
});
});
}
function help() {
console.log('[usage] node xmlrun [xml file]');
}
function Node(parent, type, tag, attrs, val, child, depth) {
this._type = type;
this._depth = depth;
if(!!parent) this._parent = parent;
if(!!tag) this._tag = tag;
if(!!attrs) {
this._attr = {};
for(let i=0; i<attrs.length; i++) {
this._attr[attrs.item(i).name] = attrs.item(i).value;
}
}
this._val = '';
if(!!child) {
this._child = [];
for(let i=0; i<child.length; i++) {
switch(child[i].nodeType) {
case 1:
this._child.push(new Node(this, child[i].nodeType, child[i].tagName, child[i].attributes, child[i].nodeValue, child[i].childNodes, depth+1));
break;
case 3:
if(!!child[i].nodeValue && child[i].nodeValue.trim().length > 0) this._val += child[i].nodeValue.trim();
break;
default:
console.log('node type: ', child[i].nodeType);
break;
}
}
}
this._run = function(target) {
console.log(indent(this._depth) + `${this._type}, ${!!this._parent?this._parent._tag:''}, ${this._tag}, ${this._val}, ${this._depth}`);
if(!!target._attr) console.log(indent(this._depth+1) + JSON.stringify(target._attr).substr(0, 50) + '...');
if(!!this._child)
this._child.forEach(c => c.run());
}
this.run = function() {
this._run(this);
};
}
function indent(n) {
let ret = '';
for(let i=0; i<n; i++) ret+='\t';
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment