Reading in a local csv file in javascript?
Here is how to use the readAsBinaryString()
from the FileReader API to load a local file.
Basically, just need to listen to change event in <input type="file">
and call the readFile function.
const fileInput = document.getElementById('csv')
const readFile = () => {
const reader = new FileReader()
reader.onload = () => {
document.getElementById('out').innerHTML = reader.result
}
// start reading the file. When it is done, calls the onload event defined above.
reader.readAsBinaryString(fileInput.files[0])
}
fileInput.addEventListener('change', readFile)
<div>
<p>Select local CSV File:</p>
<input id="csv" type="file" accept=".csv">
</div>
<pre id="out"><p>File contents will appear here</p></pre>
jsFiddle
There are as many ways of accomplishing what you want as you could possibly imagine.
If I were doing this, I might start by splitting the input text into lines like so:
var lines = inputText.split('\n');
Then, I would extract the names of the headers from the first line. You need a function to read the values from each line.
// This assumes no commas in the values names.
function getCsvValuesFromLine(line) {
var values = line[0].split(',');
value = values.map(function(value){
return value.replace(/\"/g, '');
});
return values;
}
var headers = getCsvValuesFromLine(lines[0]);
Next, I would loop over the remaining lines and create an array of objects representing the values in the lines.
lines.shift(); // remove header line from array
var people = lines.map(function(line) {
var person = {};
var lineValues = getCsvValuesFromLine(line);
for (var i = 0; i < lines.length; i += 1) {
person[headers[i]] = lineValues[i];
}
return person;
});
If this all works, you should end up with an array of objects representing the values in each line in your CSV.
The above is a rough outline of what the code might look like. I have not tested it and it certainly is not production ready, but I hope it gives you an idea of how to go about doing what you want.
I've used several built-in Javascript functions. I suggest looking them up on MDN if you're not familiar with them; they are good to know.
Finally, there is an odd quirk in Javascript with its automatic semi-colon insertion (a bad feature of the language, IMO). In order to avoid problems, do not put a new-line before an opening brace.
Always write
XXXX {
....
}
and don't write
XXXX
{
....
}