100 lines
2.0 KiB
JavaScript
100 lines
2.0 KiB
JavaScript
"use strict";
|
|
|
|
/**
|
|
* Minimal, dependency-free RFC 4180 CSV parser.
|
|
* Handles quoted fields, escaped quotes (""), commas and newlines inside
|
|
* quotes, and both \n and \r\n line endings.
|
|
*
|
|
* Returns an array of row objects keyed by the header row. Rows with a
|
|
* different column count than the header are skipped (not thrown), since
|
|
* real billing-provider exports occasionally have a trailing blank line.
|
|
*/
|
|
function parseCsv(text) {
|
|
const rows = parseRows(text);
|
|
if (rows.length === 0) return { headers: [], records: [] };
|
|
|
|
const headers = rows[0].map((h) => h.trim());
|
|
const records = [];
|
|
|
|
for (let i = 1; i < rows.length; i++) {
|
|
const row = rows[i];
|
|
if (row.length === 1 && row[0] === "") continue; // trailing blank line
|
|
const record = {};
|
|
for (let c = 0; c < headers.length; c++) {
|
|
record[headers[c]] = row[c] !== undefined ? row[c] : "";
|
|
}
|
|
records.push(record);
|
|
}
|
|
|
|
return { headers, records };
|
|
}
|
|
|
|
function parseRows(text) {
|
|
const rows = [];
|
|
let row = [];
|
|
let field = "";
|
|
let inQuotes = false;
|
|
let i = 0;
|
|
const len = text.length;
|
|
|
|
while (i < len) {
|
|
const ch = text[i];
|
|
|
|
if (inQuotes) {
|
|
if (ch === '"') {
|
|
if (text[i + 1] === '"') {
|
|
field += '"';
|
|
i += 2;
|
|
continue;
|
|
}
|
|
inQuotes = false;
|
|
i++;
|
|
continue;
|
|
}
|
|
field += ch;
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if (ch === '"') {
|
|
inQuotes = true;
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if (ch === ",") {
|
|
row.push(field);
|
|
field = "";
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if (ch === "\r") {
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if (ch === "\n") {
|
|
row.push(field);
|
|
rows.push(row);
|
|
row = [];
|
|
field = "";
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
field += ch;
|
|
i++;
|
|
}
|
|
|
|
// last field/row (file may or may not end with a newline)
|
|
if (field !== "" || row.length > 0) {
|
|
row.push(field);
|
|
rows.push(row);
|
|
}
|
|
|
|
return rows;
|
|
}
|
|
|
|
module.exports = { parseCsv };
|