Read CSV Files In NodeJS (Very Simple Examples)

Welcome to a quick tutorial on how to read CSV files in NodeJS. Need to read some data from a CSV file in Node? Well, it is a piece of cake.

One of the easiest ways is to use the CSV parser module.

  • npm install csv-parser
  • Then load the required modules.
    • const fs = require("fs");
    • const csv = require("csv-parser");
  • Lastly, just pipe a read stream to the CSV parser.
    • fs.createReadStream("FILE.CSV")
    • .pipe(csv())
    • .on("data", data => { DO SOMETHING });

That covers the basics, but read on for more examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

READ CSV FILES IN NODEJS

All right, let us now get into the examples of how to read CSV files in NodeJS.

 

EXAMPLE 1) READ CSV INTO AN OBJECT

1A) DUMMY CSV

1a-dummy.csv
Animal,Description
Doge,Good Boy
Cate,Evil
Birb,Happy Wings

For this example, we will be using a list of meme animals – The first row is the header.

 

1B) CSV PARSER INTO OBJECT

1b-csv-object.js
// (A) LOAD REQUIRED MODULES
// npm install csv-parser
// https://www.npmjs.com/package/csv-parser
const fs = require("fs"),
      csv = require("csv-parser");
 
// (B) READ CSV FILE
var results = [];
fs.createReadStream("1a-dummy.csv")
.pipe(csv())
.on("data", data => results.push(data))
.on("end", () => console.log(results));
The result
[
  { Animal: 'Doge', Description: 'Good Boy' },
  { Animal: 'Cate', Description: 'Evil' },
  { Animal: 'Birb', Description: 'Happy Wings' }
]

Don’t think this needs a lot of explanation.

  1. Load the required modules – The file system and CSV parser.
  2. Open the dummy CSV file, pipe it to the CSV parser, and read it into an object. CSV parser will automatically use the first row as the object keys – [{ HEAD : VALUE }, { HEAD : VALUE }, ...]

 

 

EXAMPLE 2) READ CSV INTO AN ARRAY

2A) DUMMY CSV

2a-dummy.csv
Apple,Banana
Cherry,Durian
Elderberry,Fig

For this example, we have a different example CSV – Take note that there are no headers. Only a list of fruits.

 

2B) CSV PARSER INTO NUMERIC INDEXED OBJECT

2b-csv-array.js
// (A) LOAD REQUIRED MODULES
// npm install csv-parser
// https://www.npmjs.com/package/csv-parser
const fs = require("fs"),
      csv = require("csv-parser");
 
// (B) READ CSV FILE
var results = [];
fs.createReadStream("2a-dummy.csv")
.pipe(csv({ headers : false }))
.on("data", data => results.push(data))
.on("end", () => console.log(results));
The result
[
  { '0': 'Apple', '1': 'Banana' },
  { '0': 'Cherry', '1': 'Durian' },
  { '0': 'Elderberry', '1': 'Fig' }
]

The only difference here is csv({ headers : false }), we tell the CSV parser that the first row is not a header. But take note, CSV parser now returns a number indexed object instead.

 

2C) CSV PARSER INTO ARRAY

2c-csv-array.js
// (A) LOAD REQUIRED MODULES
// npm install csv-parser
// https://www.npmjs.com/package/csv-parser
const fs = require("fs"),
      csv = require("csv-parser");
 
// (B) READ CSV FILE
var results = [];
fs.createReadStream("2a-dummy.csv")
.pipe(csv({ headers : false }))
.on("data", data => results.push(Object.values(data)))
.on("end", () => console.log(results));
The result
[
  [ 'Apple', 'Banana' ],
  [ 'Cherry', 'Durian' ],
  [ 'Elderberry', 'Fig' ]
]

If you want to read the CSV file as a “flat array”, we simply have to do a bit of “data yoga” – Object.values(data) will do the trick.

 

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Read CSV Files In NodeJS (Very Simple Examples)”

  1. The first 2 approaches have one bug around the fact that you can have commas as cell value and the split will split the line in more cells. you will need a regex for this one.

    1. Thanks for reporting, completely forgot about that. Will add regex to check for “comma enclosed in quotes” in a future update.

Leave a Comment

Your email address will not be published. Required fields are marked *