How would you process a very large CSV file in Node.js without loading the entire file into memory?
Short answer
Combining a readable file stream with a line-by-line or CSV-specific parsing library (like csv-parse in streaming mode) lets you process each row as it's read, rather than waiting for and holding the entire file in memory -- this is essential for files too large to fit…
Advertisement
AModel answer
Combining a readable file stream with a line-by-line or CSV-specific parsing library (like csv-parse in streaming mode) lets you process each row as it's read, rather than waiting for and holding the entire file in memory -- this is essential for files too large to fit comfortably in memory, and lets processing begin immediately rather than waiting for the entire file to load first.
const fs = require('node:fs');
const { parse } = require('csv-parse');
fs.createReadStream('huge-data.csv')
.pipe(parse({ columns: true }))
.on('data', (row) => { processRow(row); })
.on('end', () => console.log('Finished processing'));Real-world example
A data-import tool processes a multi-gigabyte CSV file of customer records by streaming it through csv-parse and inserting each row into the database as it's parsed, rather than attempting to load and parse the entire file into an array first, which had previously caused out-of-memory crashes.
Likely follow-ups
- How would you add backpressure-aware batching, inserting rows in batches of 1000 rather than one at a time, to this streaming pipeline?
- What happens if a single malformed row in the middle of a huge file causes a parsing error?
Related topics