Processing large CSV files without running out of memory

Reading the whole file before parsing it is the usual cause. Streams keep memory flat no matter the size.

An import job that works with a 10 MB file and crashes with a 2 GB one is almost always loading everything into memory first: readFile, then split('\n'), then an array of rows.

Stream it

Node can read the file in chunks and hand each line to your code as it arrives. Memory stays proportional to one chunk, not to the file.

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

const lines = createInterface({ input: createReadStream('orders.csv') });

for await (const line of lines) {
  await batch.add(parse(line));
}
await batch.flush();

Batch the writes

One insert per row is the next bottleneck. Group rows into batches of a few hundred and insert them together. for await also gives you backpressure for free: the file is not read faster than the database can take it.