@maukode/siesvi
Version:
siesvi is CSV library that use typescript and provide CSV common functions from parsing, validation, to transformation.
53 lines (52 loc) • 2.57 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CsvValidator = void 0;
const stream_1 = require("stream");
class CsvValidator extends stream_1.Transform {
constructor(config = {}) {
super({ objectMode: true });
this.header = null;
this.rowCount = 0;
this.config = {
delimiter: config.delimiter || ',',
expectedHeader: config.expectedHeader,
minColumns: config.minColumns,
maxColumns: config.maxColumns,
};
}
_transform(chunk, encoding, callback) {
try {
const lines = chunk.toString(encoding).split('\n').filter(line => line.trim() !== ''); // Remove empty lines
for (const line of lines) {
const row = line.split(this.config.delimiter);
this.rowCount++;
if (!this.header) {
this.header = row.map(header => header.trim()); // Trim headers
if (this.config.expectedHeader) {
if (this.config.expectedHeader.length !== this.header.length) {
return callback(new Error(`Header column count mismatch. Expected ${this.config.expectedHeader.length}, got ${this.header.length} on line ${this.rowCount}`));
}
for (let i = 0; i < this.config.expectedHeader.length; i++) {
if (this.config.expectedHeader[i].trim() !== this.header[i]) {
return callback(new Error(`Header mismatch at column ${i + 1}. Expected '${this.config.expectedHeader[i].trim()}', got '${this.header[i]}' on line ${this.rowCount}`));
}
}
}
continue;
}
if (this.config.minColumns !== undefined && row.length < this.config.minColumns) {
return callback(new Error(`Row ${this.rowCount} has too few columns. Expected at least ${this.config.minColumns}, got ${row.length}`));
}
if (this.config.maxColumns !== undefined && row.length > this.config.maxColumns) {
return callback(new Error(`Row ${this.rowCount} has too many columns. Expected at most ${this.config.maxColumns}, got ${row.length}`));
}
this.push(chunk);
}
callback();
}
catch (error) {
callback(error);
}
}
}
exports.CsvValidator = CsvValidator;