Streaming 1 GiB CSV Diffs in a Web Worker Without Corrupting Leading Zeros
Reconciling two large CSV exports in the browser usually fails in one of three ways: Calling await file.text() on two 400 MB files blows past the tab heap limit before parsing even starts. Coercing cells with Number() or parseFloat() turns invoice ID "00123" into 123 and hides real mismatches. Indexing rows with map.set(key, row) silently overwrites duplicate keys—which in finance or…
Reconciling large CSV exports in the browser can be tricky. Loading entire 400 MB files at once often exceeds the tab heap limit before parsing even begins. Directly converting cells to numbers using Number() or parseFloat() converts invoice IDs like "00123" into 123, masking actual differences. Sequentially indexing rows with map.set(key, row) can silently overwrite duplicate keys, which are often crucial for catching errors in finance or order-vs-payment exports.
The author outlines a Web Worker architecture to diff files up to 1 GiB locally while maintaining precise raw-string matching and bounded memory usage. They stream file chunks using file.stream() and a TextDecoder with fatal error handling to avoid silent corruption of encoding-sensitive keys. Chunk boundaries are critical, as \r\n sequences or quoted multiline fields can split across chunks. Properly tracking quoted, closed, and skipLF states across iterations ensures accurate comparison.
The design guards against V8's sliced-string heap trap, where slicing substrings in large decoded chunks can pin parent chunk strings in memory. Force-copying cell values prevents retained keys and values from being discarded along with the chunk buffers. An explicit character budget for indexed units is tracked during streaming to alert users if the selected columns exceed memory limits.
The key serialization process avoids coercing keys and prevents accidental overwriting of duplicates. Raw strings are serialized directly, preserving leading zeros like "00123" and preventing mismatched matches with "123". Blank key cells are separated into a distinct list instead of incorrectly matching each other. Each key maps to a pair of arrays for rows from the first and second files.
During classification, rows with identical counts in both files are compared directly, while unmatched keys are routed for review to ensure duplicate IDs aren't silently dropped.
The Worker design ensures the reconciliation state is disposable. Cancelling a job or switching files simply calls worker.terminate(), releasing the entire heap immediately. The final classified rows are streamed into a Blob and revoked on pagehide. The author has packaged this Worker into a browser-only tool at fileminto.com/csv/compare, allowing local comparison without uploads, demonstrating its effectiveness for large tabular diffs in the browser, particularly with mixed encodings or composite keys.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to