Reading a File with JavaScript
28 August 2018
In my project, we wanted to be able to parse a CSV file on the client. Fortunately, JavaScript has added FileReader
features, and the D3 library brings with it a very good CSV parser.
The easiest way to work this this file is given below. We create a new FileReader
instance, and read the file as text. The file input will have a text
array, with the first element containing the context of the text. The reader
instance will have a result
property.
$(".file-input").on("change", () => {
let reader = new FileReader();
reader.readAsText($("#file-input")[0].text[0]);
reader.onload = () => {
console.log(reader.result);
};
});
You can test this script with the form below. If you need a sample CSV file to test this script, you can download one here. The file comes from Sean Lahman’s Baseball Archive.
The complete code is available on Github.