xml plugin initial import

This commit is contained in:
Jan Prochazka
2022-01-30 10:30:47 +01:00
parent 94351805d3
commit 09f5e3e703
15 changed files with 3915 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
const reader = require('./reader');
const writer = require('./writer');
module.exports = {
packageName: 'dbgate-plugin-xml',
shellApi: {
reader,
writer,
},
};

View File

@@ -0,0 +1,42 @@
const fs = require('fs');
const stream = require('stream');
const NodeXmlStream = require('node-xml-stream');
class ParseStream extends stream.Transform {
constructor({ elementName }) {
super({ objectMode: true });
this.rowsWritten = 0;
this.parser = new NodeXmlStream();
this.stack = [];
this.parser.on('opentag', (name, attrs) => {
this.stack.push({ name, attrs, nodes: {} });
});
this.parser.on('text', (text) => {
if (this.stack.length >= 2) {
this.stack[this.stack.length - 2].nodes[this.stack[this.stack.length - 1].name] = text;
}
});
this.parser.on('closetag', (name, attrs) => {
if (name == elementName) {
this.rowsWritten += 1;
this.push({ ...this.stack[this.stack.length - 1].attrs, ...this.stack[this.stack.length - 1].nodes });
}
this.stack.splice(-1);
});
}
_transform(chunk, encoding, done) {
this.parser.write(chunk);
done();
}
}
async function reader({ fileName, encoding = 'utf-8', elementName }) {
console.log(`Reading file ${fileName}`);
const fileStream = fs.createReadStream(fileName, encoding);
const parser = new ParseStream({ elementName });
fileStream.pipe(parser);
return parser;
}
module.exports = reader;

View File

@@ -0,0 +1,23 @@
const fs = require('fs');
const stream = require('stream');
class StringifyStream extends stream.Transform {
constructor() {
super({ objectMode: true });
}
_transform(chunk, encoding, done) {
this.push(JSON.stringify(chunk) + '\n');
done();
}
}
async function writer({ fileName, encoding = 'utf-8' }) {
console.log(`Writing file ${fileName}`);
const stringify = new StringifyStream();
const fileStream = fs.createWriteStream(fileName, encoding);
stringify.pipe(fileStream);
stringify['finisher'] = fileStream;
return stringify;
}
module.exports = writer;