So I am trying to do some client side validation on an app I am working on, and I want to be able to check the number of columns in a CSV that the user uploads. The CSVs could potentially be very large (up to 30 thousand rows) so I'm worried that my current method, which reads the entire file, is not the best way to do it.
This is what I have right now.
// Function to validate the File Upload
$(document).ready(function() {
$("#csv").change(function () {
console.log("Read CSV Function Triggered");
let theFile = document.getElementById("csv").files[0];
let reader = new FileReader();
reader.addEventListener('load', readFile);
reader.readAsText(theFile);
function readFile(event) {
let csvText = event.target.result;
let firstLine = csvText.split('\n').shift(); // First Line
$("#result").html(firstLine);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="csv" />
<br>
<span id="result">0</span>
In the example I just make the first line display on the page, but in the app I have a parser library that I couldn't include in this example which converts the first line to an array and then I get the length of the array. So like I said before, this works, but I am worried that when large CSVs are uploaded it may affect browser performance.
Any suggestions?