How To Read CSV Files In NodeJS (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, we don’t actually need to use any third-party modules.

The common ways to read CSV files in NodeJS are:

  1. Read the entire CSV file into a string, then split it into an array.
    • var data = require("fs").readFileSync("FILE.CSV", "utf8")
    • data = data.split("\r\n")
    • for (let i of data) { data[i] = data[i].split(",") }
  2. Read the CSV file line-by-line into an array.
    • var stream = require("fs").createReadStream("FILE.CSV")
    • var reader = require("readline").createInterface({ input: stream })
    • var arr = []
    • reader.on("line", (row) => { arr.push(row.split(",")) })

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

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Read CSV Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

READ CSV IN NODEJS

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

 

1) READ CSV INTO ARRAY

1-read-array.js
// (A) FILE SYSTEM MODULE
const fs = require("fs");
 
// (B) READ CSV INTO STRING
var data = fs.readFileSync("dummyA.csv", "utf8");
 
// (C) STRING TO ARRAY
data = data.split("\r\n"); // SPLIT ROWS
for (let i in data) { // SPLIT COLUMNS
  data[i] = data[i].split(",");
}
console.log(data);

This is the “full example” of the above snippet in the introduction. For the beginners who don’t catch the process:

  • (A & B) We read the entire CSV file as a string into var data.
  • (C) A “two-layer split” on the string to turn it into a nested array.
    • data = data.split("\r\n") will separate the rows, turning data into an array.
    • data[i] = data[i].split(",") will further separate the individual columns of each row.

 

 

2) READ CSV INTO ARRAY (LINE BY LINE)

2-stream-array
// (A) FILE SYSTEM + READ LINE MODULES
const fs = require("fs"),
      rl = require("readline");
 
// (B) FILE STREAM
const reader = rl.createInterface({
  input: fs.createReadStream("dummyA.csv")
});

// (C) READ LINE-BY-LINE INTO ARRAY
var arr = [];
reader.on("line", (row) => {
  arr.push(row.split(","));
});

// (D) DONE - FULL ARRAY
reader.on("close", () => {
  console.log(arr);
});

The previous example works, but it has a rather critical flaw – It is not a good idea to read an entire massive CSV file, it will probably run into “out-of-memory” problems. This second example is a “roundabout” way to read the CSV file row-by-row instead.

 

3) READ CSV USING CSV PARSER

3-parser.js
// (A) CSV PARSER MODULE
// 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("dummyB.csv")
.pipe(csv())
.on("data", (data) => results.push(data))
.on("end", () => {
  console.log(results);
});

Lastly, there are plenty of “CSV parsers” and “CSV readers”. We don’t actually need to use them, but they do somewhat make things easier.

 

 

USEFUL BITS & LINKS

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

 

INFOGRAPHIC CHEAT SHEET

Read CSV FIles In NodeJS (click to enlarge)

 

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 “How To Read CSV Files In NodeJS (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.