Importing and exporting .csv files in Javascript with Papa Parse

NicolasBrondinBernard

Author
@NicolasBrondinBernard

It sometimes feels like being a developer just means building data import/export modules...

Article published on 29/10/2020, last updated on 10/08/2026

When you're a web developer, the first instinct when you have data to import is to use the JSON format, natively handled in Javascript.

Unfortunately, editing such a file is not always accessible for most people, and even when someone makes the effort to do it properly, there's a good chance of ending up with syntax errors during import.

That's why .csv files are convenient: they can be edited directly in Excel, and imported very easily in Javascript thanks to the Papa Parse library.

Here's the link to the library's documentation: https://www.papaparse.com/

How does it work?

First, you need to add the library to the project's dependencies using a packet manager (such as NPM or Yarn):

npm install papaparse

For information, the examples below run on NodeJS, but the library also works very well in the browser with an input type="file"!

Importing a .csv file

Before trying to import a .csv file, check that the file is valid and that it is indeed present at the path indicated in the code, then copy-paste the code below into a javascript file and run it!

// import.js
const Papa = require("papaparse"),
  fs = require("fs");
  
try {
  let csv = fs.readFileSync("./source.csv", "utf-8")
  let csv_json = Papa.parse(csv, {encoding: "utf-8"})
  console.log(csv_json.data);
} catch(e){
  console.error(e);
}

You should see the content of your csv file appear in the console in the form of a JSON array, where each element itself contains an array of all the data from a single line of the original csv file.

If the first line of your csv file contains the headers, all you have to do is reconstruct your JSON objects based on the first line of the array!

Exporting a .csv file

Exporting JSON data to a CSV file is just as easy as importing, it only takes a few lines of code like the example below.

// export.js
const Papa = require("papaparse"),
  fs = require("fs");
  
  let json_data = [
  {firstname: "James", lastname: "Donnie", email:"jamesdonnie@example.com"},
  {firstname: "Thomas", lastname: "Crown", email:"thomascrown@example.com"},
]
try {
  var csv_data = Papa.unparse(json_data);
  fs.writeFile("./export.csv", csv_data, { flag: 'w' }, function(){
    console.log(csv_data);
  });
} catch(e){
  console.error(e);
}

Warning, the first line of the exported csv file (the headers) will correspond to the keys of the first object in the array, if some keys are present in the following objects but not in the first, they will not appear in the exported file.


Isaac Smith sur Unsplash

Finished reading this article?
Our newsletter

No spam. Only free content, news, and ever more resources to level up your skills!

Join +1500 developers

Comments (0)

to leave a comment

No comments yet