Reading in a local csv file in javascript?

ocean800 picture ocean800 · Apr 1, 2015 · Viewed 84.6k times · Source

[EDIT] I solved the problem using D3, nevermind thanks!

So I have a csv file that looks something like this, and I need to import a local csv file into my client side javascript:

    "L.Name", "F.Name", "Gender", "School Type", "Subjects"
    "Doe",    "John",  "M",      "University",  "Chem I, statistics, English, Anatomy"
    "Tan",    "Betty",   "F",     "High School", "Algebra I, chem I, English 101"
    "Han",    "Anna",    "F",     "University",  "PHY 3, Calc 2, anatomy I, spanish 101"
    "Hawk",   "Alan",    "M",     "University",  "English 101, chem I" 

I eventually need do parse it and output something like:

Chem I: 3         (number of people taking each subject)
Spanish 101: 1 
Philosophy 204: 0 

But for now, I am stuck on just importing it into javascript.

My current code looks like this:

<!DOCTYPE html>  
<html>  
<body>
<h1>Title!</h1>
<p>Please enter the subject(s) that you wish to search for:</p>
<input id="numb" type="text"/> 
<button onclick="myFunction()">Click me to see! :) </button>
<script>
function myFunction() {
    var splitResearchArea = []; 
    var textInput = document.getElementById('numb').value; 
    var splitTextInput = textInput.split(",");

  for(var i =0; i<splitTextInput.length; i++) {
    var spltResearchArea = splitTextInput[i];
    splitResearchArea.push(spltResearchArea);
  }
}

I've researched and found some helpful links on Stackoverflow like this, this, and this but I'm new to javascript and I don't completely understand it. Should I use Ajax? FileReader? jQuery? What are the benefits of using one over the other? And how would you implement this in code?

But yeah, I'm just confused since I'm very new to javascript, so any help in the right direction would be great. Thank you!!

Answer

Jose Rui Santos picture Jose Rui Santos · Apr 1, 2015

Here is how to use the readAsBinaryString() from the FileReader API to load a local file.

<p>Select local CSV File:</p>
<input id="csv" type="file">

<output id="out">
    file contents will appear here
</output>

Basically, just need to listen to change event in <input type="file"> and call the readFile function.

var fileInput = document.getElementById("csv"),

    readFile = function () {
        var reader = new FileReader();
        reader.onload = function () {
            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);

jsFiddle