Reading in a local csv file in javascript?

Posted by ExiaHuang on July 30, 2017

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

1
2
3
4
5
6
<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.

1
2
3
4
5
6
7
8
9
10
11
12
13
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]);
        reader.readAsText(fileInput.files[0], 'utf8');
    };

fileInput.addEventListener('change', readFile);