Large CSV in JavaScript: Convert to JSON Without Freezing
How to read a CSV of hundreds of MB in the browser with streams, a Web Worker or Papa Parse, without freezing the tab or splitting rows between chunks.
I got a 180 MB CSV of financial transactions and needed it as JSON to feed a pipeline. The first version of my script loaded the whole file with file.text(), called split('\n') and built one giant array. The tab froze, Chrome offered "Wait or Exit page", and I exited.
If you're here with the same problem, the short answer is: read the file as a stream (file.stream() + TextDecoder), feed the chunks to a parser that keeps its state from one chunk to the next, and run all of it inside a Web Worker that reports progress in batches instead of sending back the whole result at once. If you'd rather not write the parser, Papa Parse does this with worker: true and step. The rest of this post builds each piece and points out where the traps are.
Why the tab freezes
Your page's JavaScript runs on the main thread, the same thread that paints the screen and handles clicks. While your code reads 180 MB, splits it into lines and calls JSON.stringify on hundreds of thousands of objects, nothing else happens: no scrolling, no animations, no working cancel button.
There are two separate problems here, and it helps to keep them apart:
- CPU time on the main thread. Even if the file fits in memory, processing it in one go blocks the UI. The fix is moving the work off the main thread (a Worker).
- Memory.
file.text()creates a string with the entire file,splitmakes another copy in pieces, and the array of objects takes several times the original size. The fix is reading as a stream and dropping what you've already processed.
The classic mistake: slicing the file and calling split('\n')
Almost everyone's first idea (mine included) is to cut the file into blocks with file.slice(), read each block as text and split on \n. It looks like streaming, but it has two bugs that only show up with real data:
- The line cut in half. A block ends wherever the byte count says, not where the line ends. The last line of each block comes out truncated, and so does the first line of the next one. You get two broken records.
- The character cut in half. In UTF-8,
étakes 2 bytes and€takes 3. If the cut lands between them, each half is decoded separately and turns into�.
I tried this on a small CSV read in 7-byte blocks: the file had 6 logical lines (header plus 5 records) and split returned 23 "lines", several with � where an accented letter should be. And there's a third problem that has nothing to do with blocks: a quoted field can contain a line break ("Main St\nApt 2"), so split('\n') gets it wrong even when you read the whole file.
Reading as a stream with file.stream() and TextDecoder
Blob.stream() (and File inherits from Blob) returns a ReadableStream of bytes. According to MDN, it has worked across all major browsers since April 2021, and it's also available inside Web Workers.
To turn bytes into text without splitting characters, use TextDecoder.decode(chunk, { stream: true }). With that option the decoder holds on to the bytes of an incomplete character and only emits it when the next chunk arrives. At the end, one decode() call with no arguments flushes whatever is left.
async function readCsv(file, { sep = ',', encoding = 'utf-8', onRow, onProgress }) {
const decoder = new TextDecoder(encoding, { fatal: encoding === 'utf-8' });
const parser = createCsvParser(sep, onRow);
const reader = file.stream().getReader();
let bytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.byteLength;
parser.push(decoder.decode(value, { stream: true }));
onProgress?.(bytes, file.size);
}
parser.push(decoder.decode()); // flush whatever the decoder is holding
parser.end();
return bytes;
}
Two details in that code:
fatal: trueon UTF-8 makes the decoder throw aTypeErroron invalid bytes instead of silently swapping them for�. We'll use that to detect CSVs that Excel saved as Windows-1252 (more on that below).- You don't choose the size of the chunks the stream hands you. That's why progress is measured in bytes read, not in lines.
If you don't need the byte counter, the TextDecoderStream version (available across major browsers since September 2022, per MDN) is shorter:
const reader = file.stream().pipeThrough(new TextDecoderStream()).getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
parser.push(value); // value is already a string
}
parser.end();
A parser that survives chunk boundaries
The decoder handles the split character. The split line and the quoted line break are the parser's job, and that parser has to be a state machine: it reads one character at a time and keeps the current field and row between one push call and the next. That way it doesn't matter where a chunk ends.
function createCsvParser(sep, onRow) {
let field = '';
let row = [];
let state = 'start'; // start | field | quoted | quoteInQuoted
let skipLF = false; // \r at the end of one chunk, \n at the start of the next
function endField() { row.push(field); field = ''; }
function endRow() {
endField();
if (row.length > 1 || row[0] !== '') onRow(row); // skip empty lines
row = [];
state = 'start';
}
function push(text) {
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (skipLF) { skipLF = false; if (ch === '\n') continue; }
if (state === 'quoted') {
if (ch === '"') state = 'quoteInQuoted';
else field += ch;
continue;
}
if (state === 'quoteInQuoted') {
if (ch === '"') { field += '"'; state = 'quoted'; continue; } // "" becomes "
state = 'field'; // the quote closed the field; fall through to normal handling
}
if (ch === '"' && state === 'start') { state = 'quoted'; continue; }
if (ch === sep) { endField(); state = 'start'; continue; }
if (ch === '\n' || ch === '\r') { skipLF = ch === '\r'; endRow(); continue; }
field += ch;
state = 'field';
}
}
function end() {
if (field !== '' || row.length > 0 || state !== 'start') endRow();
}
return { push, end };
}
The quoteInQuoted state exists for one specific reason: a quote inside a quoted field can be the end of the field or the first half of "" (an escaped quote). If it's the last character of a chunk, you can only tell once the next chunk arrives.
I ran these two functions on Node 24 against a CSV with a BOM, \r\n line endings, a semicolon inside quotes, a line break inside a field, an escaped "", accented letters, € and an emoji, delivering the file in chunks of 1, 2, 3, 5, 7 and 64 bytes. Every run produced exactly what Papa Parse produced. The BOM goes away on its own: TextDecoder skips it by default.
Moving it into a Web Worker
Streaming fixes the memory cost of reading, but parsing still runs on the main thread. A Worker takes that work elsewhere. The part people usually get wrong is the way back: don't build the full array and send it with a single postMessage. Everything that crosses postMessage is copied (structured clone), and copying an array of a million objects is exactly the kind of heavy work you were trying to get off the main thread.
What works better is having the worker build the JSON as text, piece by piece, and only send progress along the way. At the end it hands over a Blob ready to download.
// csv-worker.js (paste createCsvParser and readCsv at the top of this file)
const BATCH = 5000;
async function convert(file, sep, encoding) {
let headers = null;
let rows = 0;
let badRows = 0;
let batch = [];
const parts = ['['];
function flush(bytes) {
parts.push(batch.join(''));
batch = [];
self.postMessage({ type: 'progress', rows, bytes, total: file.size });
}
await readCsv(file, {
sep,
encoding,
onRow(fields) {
if (!headers) { headers = fields.map((h) => h.trim()); return; }
if (fields.length !== headers.length) { badRows++; return; }
const obj = {};
headers.forEach((h, i) => { obj[h] = fields[i]; });
batch.push((rows === 0 ? '' : ',') + JSON.stringify(obj));
rows++;
},
onProgress(bytes) {
if (batch.length >= BATCH) flush(bytes);
},
});
flush(file.size);
parts.push(']');
return { blob: new Blob(parts, { type: 'application/json' }), rows, badRows };
}
self.onmessage = async ({ data: { file, sep } }) => {
try {
let result;
try {
result = await convert(file, sep, 'utf-8');
} catch (err) {
if (!(err instanceof TypeError)) throw err;
// Invalid UTF-8 bytes: most likely a CSV that Excel saved as Windows-1252
result = await convert(file, sep, 'windows-1252');
}
self.postMessage({ type: 'done', ...result });
} catch (err) {
self.postMessage({ type: 'error', message: String(err) });
}
};
And on the page side:
const worker = new Worker('/csv-worker.js');
worker.onmessage = ({ data }) => {
if (data.type === 'progress') {
progressBar.value = data.bytes / data.total;
status.textContent = `${data.rows.toLocaleString('en-US')} rows`;
}
if (data.type === 'done') {
const a = document.createElement('a');
a.href = URL.createObjectURL(data.blob);
a.download = 'data.json';
a.click();
status.textContent = `${data.rows} rows converted, ${data.badRows} skipped`;
}
if (data.type === 'error') status.textContent = data.message;
};
input.addEventListener('change', () => {
worker.postMessage({ file: input.files[0], sep: ',' });
});
About handing the File to the worker: it is not a transferable object. MDN's list of transferables includes ArrayBuffer, MessagePort, ReadableStream and others, but not File or Blob. The File goes through structured clone, which supports both types. For your code nothing changes: the worker gets a File and reads it with stream() itself. Just don't put the File in postMessage's second argument thinking you're transferring it.
I tested this worker in Node with a stubbed self: a 17 MB CSV with 250,000 rows (each with a comma inside quotes, an escaped "" and a line break inside a field) became JSON that matched Papa Parse's output record for record, and the one row with the wrong number of columns was counted in badRows. A Latin-1 file containing "João" and "São Paulo" hit the Windows-1252 fallback and came out with the accents intact.
How far this actually goes
This design gets parsing off the main thread and avoids loading the CSV as one big string. But the output JSON is still assembled in the worker's memory, piece by piece, until it becomes a Blob. For hundreds of MB that's fine. For several GB, the question changes: do you really need one JSON file with everything in it?
- If the target is an import, emit JSON Lines (one object per line, no
[]and no commas): swap the','separator for'\n'and drop the brackets. The consumer can then read it as a stream too, instead of callingJSON.parseon a huge file. - If what you want is a number (totals per category, error counts), aggregate inside
onRowand throw the row away. There's no JSON to keep. - If the file is going to a server anyway, upload the CSV and convert it there, streaming. The constant-memory logic is the same, and it's covered in the post on processing large files without running out of memory.
If you're deciding between handling records one by one or in a scheduled job, streaming vs batch processing walks through the trade-off.
Shortcut: Papa Parse with worker and step
If you don't want to maintain your own parser, Papa Parse (npm install papaparse) streams local files and runs in a worker with a single option:
import Papa from 'papaparse';
let rows = 0;
Papa.parse(file, {
worker: true, // parse off the main thread
header: true, // first row becomes the field names
skipEmptyLines: true,
// delimiter: ';', // omit to auto-detect
// encoding: 'windows-1252', // only for legacy Excel exports
step(results) {
// in step mode, results.data is ONE record (an object, with header: true)
rows++;
if (results.errors.length) console.warn(results.errors);
},
complete() {
console.log(`${rows} rows`);
},
});
What the docs say and is worth knowing before you rely on it:
stepruns once per row;chunkruns once per chunk of the file. Don't use both together.- You can stop with
parser.abort()insidestep, butparser.pause()doesn't work with a worker. - When streaming, the
completecallback doesn't receive the data. Collect (or aggregate) it instep. - With a worker, every result has to be copied from the worker thread to the main thread. If your
stepjust pushes objects into an array, you're back to the memory problem.
One gotcha I tested: with dynamicTyping: true, a ZIP code like 02134 becomes the number 2134. Leading zeros disappear, and so does every ZIP code, account number or product code that starts with one. Leave dynamicTyping off and convert only the columns you know are numeric.
Checklist before you trust the JSON
- Encoding: is the file UTF-8 or Windows-1252? Accents turning into
émean the encoding is mismatched. The post on importing CSV without corrupting characters covers BOMs, Excel and how to diagnose it. - Delimiter: Excel in many European locales saves with
;, because the comma is the decimal separator there. - Header: duplicate names or stray spaces turn into duplicate or odd keys in the JSON.
- Column count: rows with too many or too few fields should be counted and reported, not silently dropped.
- Types: numbers with a decimal comma (
1.234,56), mixed date formats and booleans written asyes/noall arrive as strings. Convert them on purpose, column by column.
Once the file is generated, paste a sample of the output into the JSON Formatter to check its structure. If it shows a syntax error, the post on how to validate JSON shows how to find the exact line.
Frequently asked questions
At what file size do streams and a Worker become worth it?
There's no magic number; it depends on the machine and on what you do with each row. A practical rule: if the file comes from someone else or from a system that can grow, write it as a stream from day one. For files of a few MB that you control, reading them whole is simpler and won't freeze anything.
Is the File transferred or copied to the Worker?
Copied, via structured clone. File and Blob aren't on MDN's list of transferable objects. In practice you just call worker.postMessage({ file }) and read the file inside the worker.
Why not just split(',') each line?
Because a quoted field can contain the delimiter itself ("Smith, John") and line breaks. For a CSV that came from a spreadsheet or a third-party system, use a parser that understands quotes: the state machine above or a library.
For everyday files
For a regular CSV you want to see as JSON right now, without writing code, Quick Tools' CSV to JSON converter does it in the browser, without sending the file to any server. It detects the delimiter (comma, semicolon, tab or pipe), handles quoted fields with line breaks, reads the file as UTF-8 and falls back to Windows-1252 when the CSV came from Excel, and has optional type inference that keeps leading zeros as text. It also goes the other way, JSON to CSV, adding a BOM to the download so Excel shows accented characters correctly.
One honest caveat: the tool reads the whole file at once and converts it in the tab itself, with no Worker and no streaming. It's great for inspecting a sample and understanding the format; for a file of hundreds of MB, use the code in this post.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.