Node.js › File System & File Processing
How would you process a very large CSV file in Node.js without loading the entire file into memory?
AdvancedAnswer
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.