← Back to Node.js, page 6

nodejs-0111 · Medium mid

Why is splitting CSV text on commas not enough, and how do you stream CSV with csv-parse, including quoted fields and bad rows?

CSV allows commas, quotes and even line breaks inside quoted fields, so line.split(',') breaks on real data. A parser such as csv-parse follows the format (RFC 4180), runs as a Transform stream, can map rows to objects with columns, and can skip or report bad rows. Use it inside pipeline or for await so memory stays flat.

Full answer

The CSV format is simple only until real data arrives:

  • A field can be quoted: "Sharma, Asha". The comma inside the quotes is data.
  • A quote inside a quoted field is written twice, as in "She said ""hi"" there".
  • A quoted field can contain a line break, so one record can span two lines. Splitting by line before parsing breaks it.
  • Files can start with a byte order mark (BOM), use semicolons or tabs, or have rows with the wrong number of fields.

csv-parse (from the csv project) is a Transform stream. Bytes go in, records come out. Important options:

  • columns: true uses the header row as property names and returns objects.
  • cast: true converts numbers and dates, or give a function for exact control. Be careful with IDs like 007.
  • trim: true removes spaces around fields.
  • bom: true removes a leading BOM.
  • delimiter for ; or tab.
  • relax_column_count and skip_records_with_error with on_skip decide what happens to bad rows. Never skip silently: count them and log the line number.
  • The error object has code, lines and record details to report to the user.

Use it with stream/promises pipeline or for await so backpressure is respected. The sync API (csv-parse/sync) is fine for small files in scripts only. Validate each record afterwards (for example with zod), because a parser checks syntax, not meaning.

javascript
const { parse } = require('csv-parse');
const { Readable } = require('node:stream');

// A header, a quoted comma, doubled quotes, a line break inside quotes, and one row with a missing field.
const text = [
  'name,city,note,marks',
  'Asha,"Pune, India","She said ""hi"" there",78',
  'Ravi,Delhi,"two',
  'lines",64',
  'Meera,Mumbai,only three fields',
  'Kabir,Chennai,ok,91',
].join('\n');

async function main() {
  // The naive way:
  const naive = text.split('\n').map((line) => line.split(','));
  console.log('naive row 2 field count:', naive[1].length, '(should be 4)');

  const skipped = [];
  const parser = Readable.from([text.slice(0, 40), text.slice(40)]).pipe(parse({
    columns: true,
    trim: true,
    cast: (value, context) => (context.column === 'marks' ? Number(value) : value),
    skip_records_with_error: true,
    on_skip: (err) => skipped.push({ code: err.code, line: err.lines }),
  }));

  const records = [];
  for await (const record of parser) records.push(record);
  for (const r of records) console.log(JSON.stringify(r));
  console.log('skipped:', JSON.stringify(skipped));
}
main();

The text is cut into two chunks in the middle of a row. The parser still returns three correct records and reports the bad row with its line number. Install first with npm install csv-parse (run here with csv-parse 7.0.3). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): naive row 2 field count: 5 (should be 4) {"name":"Asha","city":"Pune, India","note":"She said \"hi\" there","marks":78} {"name":"Ravi","city":"Delhi","note":"two\nlines","marks":64} {"name":"Kabir","city":"Chennai","note":"ok","marks":91} skipped: [{"code":"CSV_RECORD_INCONSISTENT_COLUMNS","line":5}]

Key points

  • Quoted fields can contain commas, quotes and line breaks.
  • csv-parse is a Transform stream and fits pipeline and for await.
  • columns turns rows into objects.
  • Decide on purpose what happens to bad rows, and count them.
  • Validate parsed values separately.

Common mistakes

  • Using split(',') on real CSV data.
  • Splitting the file by lines first and breaking multi-line fields.
  • Loading a whole big CSV with the sync API.
  • Skipping bad rows silently.
  • Using cast: true and turning an ID such as 007 into 7.

Follow-ups

  • How do you handle a file with a BOM or a different delimiter?
  • How would you validate each record before inserting it into a database?
  • How do you write CSV safely, including values that start with = or +?

Tips

  • Give the three tricky cases: comma, quote, line break.
  • Say that the parser is a Transform and fits pipeline.
  • Mention bad row reporting.