JavaScriptFundamental (ES6), part 2
Write and read CSV that round-trips in JavaScript
96 A CSV writer and reader that round-trip awkward fields
hardWrite rows to CSV, quoting only the fields that need it — a comma, a quote, a line break, or leading and trailing spaces — and doubling any quote inside. Then parse it back with a character-by-character state machine and prove the round trip. Show what split(',') makes of a quoted field, and what a trailing newline does to the row count.
Stuck? Three hints, smallest first
- 1. Quote when the field contains
,,", CR or LF, or when trimming it would change it. Escape a quote by doubling it. - 2. A parser cannot work line by line, because a quoted field is allowed to contain a line break.
- 3. Two states are enough: inside quotes and outside. Inside, only a quote is special.
const needsQuoting = (field) => /[",\r\n]/.test(field) || field !== field.trim();
const writeField = (value) => {
const text = value === null || value === undefined ? '' : String(value);
return needsQuoting(text) ? '"' + text.replace(/"/g, '""') + '"' : text;
};
const toCsv = (rows) => rows.map((row) => row.map(writeField).join(',')).join('\r\n');
function fromCsv(text) {
const rows = [];
let row = [];
let field = '';
let inQuotes = false;
let i = 0;
while (i < text.length) {
const ch = text[i];
if (inQuotes) {
if (ch === '"' && text[i + 1] === '"') { field += '"'; i += 2; continue; } // an escaped quote
if (ch === '"') { inQuotes = false; i += 1; continue; }
field += ch; i += 1; continue;
}
if (ch === '"') { inQuotes = true; i += 1; continue; }
if (ch === ',') { row.push(field); field = ''; i += 1; continue; }
if (ch === '\r' || ch === '\n') {
row.push(field);
rows.push(row);
row = [];
field = '';
i += ch === '\r' && text[i + 1] === '\n' ? 2 : 1;
continue;
}
field += ch; i += 1;
}
row.push(field);
rows.push(row);
return rows;
}
const rows = [
['name', 'city', 'note', 'kobo'],
['Adaeze Fabrics', 'Lagos', 'Ships Mon, Wed and Fri', '1290000'],
['Chidi "Chief" Okoro', 'Abuja', 'Said: "call before 9am"', '450000'],
['Ngozi Stores', 'Ibadan', 'Line one\nLine two', ''],
[' padded ', 'Kano', '', '7500'],
];
const csv = toCsv(rows);
const csvLines = csv.split('\r\n');
const backAgain = fromCsv(csv);
const roundTripped = JSON.stringify(backAgain) === JSON.stringify(rows);
const naiveSplit = csvLines[1].split(',').length;
const properly = backAgain[1].length;
const withTrailingBreak = fromCsv('name,city\r\nAdaeze,Lagos\r\n');
console.log(csv);
console.log('round trip :', roundTripped);
console.log('split(",") :', naiveSplit, 'fields where there are', properly);
console.log('trailing \\r\\n gives', withTrailingBreak.length, 'rows:', withTrailingBreak);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('only the field with a comma in it gets quoted', csvLines[1], 'Adaeze Fabrics,Lagos,"Ships Mon, Wed and Fri",1290000');
test('an internal quote is doubled and the whole field wrapped', csvLines[2], '"Chidi ""Chief"" Okoro",Abuja,"Said: ""call before 9am""",450000');
test('a field with a line break is quoted, so the file has more lines than rows', [csv.split('\n').length, rows.length], [6, 5]);
test('padding survives because trimming would have changed the field', csvLines[4], '" padded ",Kano,,7500');
test('and every row comes back exactly as it went in', roundTripped, true);
test('the empty fields read back as empty strings, not undefined', [backAgain[3][3], backAgain[4][2]], ['', '']);
test('splitting that line on a comma finds five fields where there are four', [naiveSplit, properly], [5, 4]);
test('a trailing line break leaves a phantom final row of one empty field', [withTrailingBreak.length, withTrailingBreak[2]], [3, ['']]);
CSV is only simple until a field contains a comma, and by then the naive writer has already produced a file that reads back with the wrong number of columns. The rule from RFC 4180 is short: quote when you must, and double a quote inside. The one addition here is quoting fields with leading or trailing spaces, because most readers strip them and a padded value would otherwise not survive the trip.
The third assertion is why a parser cannot be written as text.split('\n').map(line => line.split(',')). A quoted field may contain a line break, so the file has six lines for five rows, and any line-oriented reader tears that row in half. Scanning character by character with one boolean of state is barely more code and is actually correct.
The last assertion is the detail that shows up as an off-by-one in production: a file ending in a newline parses to one more row than it has records, and that phantom row is [''], not [], because a field always exists between delimiters. Skip a final row that is a single empty field rather than trusting the count. Note also what a round trip does not preserve — types. Everything comes back a string, including '' where a number used to be, which is why the amounts here are strings all along.