Reading csv file With JavaScript

Vanessa Fotso
3 min readMar 21, 2021

In this post I am going to share a skill I recently learned while completing a challenge. Up until now, I have never worked on a project that required me to read data from a csv file instead of a database with JavaScript. Here I am going to share one approach to do so using HTML5 and Papa parse library.

Papa parse is a JavaScript library for fast 'in-browser' CSV parsing. It is known to be very reliable and easy in parsing CSV files as it provides more advance features or options. It is supported by most modern browsers. You can check Papa parse documentation to learn all it features.

The approach I used involves first uploading the csv file using HTML5 <input type="file"> element, then use Papa parse to parse the file that can be used for further processing like sending it to the server to store the data in a database or display the data in a table.

Step 1

create an html file and include the Papa parse file in the head section. You can name your file index.html or whatever you want.

index.html

Step 2

Add a html form to upload your csv formatted file to index.html

index.html

As seen in the above code, I added some validation to the input file, adding the required attribute and accepting only file with .csv extension.

Output in-browser

Step 3

create a js file script.js that will have the code logic to parse the csv data using Papa.parse method. The method takes the file object and a config object as arguments. The config object defines settings, behavior, and callbacks used during parsing. Below are the default properties of the config object:

config object properties

You can find the description for each property here. In this post, we are only going to use two properties: the header which we will set to true to interpret the first row of the parsed data as the property or field names, and each row of the csv file will be an object of values keyed by field name. The second property we will use here is complete which is the callback function to execute when parsing is complete. The callback takes the parsed results as an argument.

script.js

The above code in the script.js file will execute once the user submit the its csv file.

Now we have a program to parse csv files. Once the file is parsed, you can manipulate the data however you want to meet your project’s requirement. As a demo, let’s parse the following csv file sample.csv

Here is the parsed data structure after running the program :

Here is the link to the source code:

I hope you find this post useful.

Until next time,

Happy coding/learning !!

Originally published at https://vanessuniq.github.io on March 21, 2021.

--

--

Vanessa Fotso

Health IT Software Engineer with broad technical exposure and passion for learning.