Skip to content
jshacks.dev
Node.js

Parse CSV with a stream

Parse a large CSV file line by line with readline and a small quote-aware field splitter in Node.js 24, and know when a quoted newline needs a real parser.

2 min read
Summarize in AI

split(',') breaks on the first quoted comma. For a big file, read it a line at a time with readline and split each line with a parser that understands quotes.

import.mjsJavaScript
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';

function parseLine(line) {
  const fields = [];
  let cur = '';
  let quoted = false;
  for (let i = 0; i < line.length; i++) {
    const c = line[i];
    if (quoted && c === '"' && line[i + 1] === '"') { cur += '"'; i++; }
    else if (c === '"') quoted = !quoted;
    else if (c === ',' && !quoted) { fields.push(cur); cur = ''; }
    else cur += c;
  }
  fields.push(cur);
  return fields;
}

const lines = createInterface({ input: createReadStream('users.csv'), crlfDelay: Infinity });
let header;
for await (const line of lines) {
  const fields = parseLine(line);
  if (!header) { header = fields; continue; }
  console.log(Object.fromEntries(header.map((h, i) => [h, fields[i]])));
}
Text
{ id: '1', name: 'Ada', note: 'likes "engines"' }
{ id: '2', name: 'Linus, T.', note: '' }

The input is the file from write CSV rows with a stream. crlfDelay: Infinity makes readline treat CRLF as one line break, so no stray carriage return ends up on the last field. Inside quotes a comma is data and a doubled quote is one literal quote, which is how the note survives. See readline line by line.

Every value is a string, so convert numbers yourself. The limit is line breaks inside quoted fields, which RFC 4180 allows: readline has already split the record by then, and this parser returns broken rows. If your files come from Excel or users who type multi-line notes, use a streaming parser such as csv-parse.

Also inAsync
Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.