flechtware_generateTracking.../csv_export.js

66 lines
1.5 KiB
JavaScript

const fs = require('fs');
const path = require('path');
class CsvExport {
/**
* @param {string} logDir - Directory where log files will be saved
* @param {string[]} headers - CSV header row
*/
constructor(filePath, headers = ['ID-Nummer', 'Datum (TT.MM.JJJ)', 'Tracking-Nr.','Versandinfos','Beilegeretoure']) {
this.filePath = filePath;
this.headers = headers;
if (!fs.existsSync(path.dirname(filePath))) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
} else {
fs.unlinkSync(filePath)
}
}
/**
* Writes a new log entry to today's CSV file
*/
add(data) {
this.ensureFileWithHeaders( this.filePath );
const row = [data.id, data.date, data.trackingNr, data.infos, data.returnTrackingNr]
.map(this.escapeCsv)
.join(';') + '\n';
fs.appendFileSync( this.filePath , row, (err) => {
if (err) {
console.error('Failed to write to csv file:', err);
}
});
}
/**
* Ensures headers are written if file doesn't exist
*/
ensureFileWithHeaders(filePath) {
if (!fs.existsSync(filePath)) {
const headerRow = this.headers.join(';') + '\n';
fs.writeFileSync(filePath, headerRow);
}
}
/**
* Escapes a value for safe CSV output
*/
escapeCsv(value) {
if (value == null) return '';
const str = String(value);
return /[",\n]/.test(str) ? `"${str.replace(/"/g, '""')}"` : str;
}
}
module.exports = CsvExport;