JSON array export file format, quick exports JSON, JSONL

This commit is contained in:
Jan Prochazka
2021-06-06 13:45:24 +02:00
parent 26ff3f45f8
commit 40440e957a
4 changed files with 93 additions and 11 deletions

View File

@@ -0,0 +1,51 @@
const fs = require('fs');
const stream = require('stream');
class StringifyStream extends stream.Transform {
constructor() {
super({ objectMode: true });
this.wasHeader = false;
this.wasRecord = false;
}
_transform(chunk, encoding, done) {
let skip = false;
if (!this.wasHeader) {
skip =
chunk.__isStreamHeader ||
// TODO remove isArray test
Array.isArray(chunk.columns);
this.wasHeader = true;
}
if (!skip) {
if (!this.wasRecord) {
this.push('[\n');
} else {
this.push(',\n');
}
this.wasRecord = true;
this.push(JSON.stringify(chunk));
}
done();
}
_flush() {
if (!this.wasRecord) {
this.push('[]\n');
} else {
this.push('\n]\n');
}
}
}
async function jsonArrayWriter({ 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 = jsonArrayWriter;