Table of contents
1.
Introduction
2.
What are CSV files?
3.
Reading CSV Files Using csv-parse
3.1.
Steps to Read CSV Files
3.2.
Code
3.3.
JavaScript
3.4.
Output
4.
Reading CSV Files Using Node.js Native Module
4.1.
Steps to Read CSV Files
4.2.
Code
4.3.
JavaScript
4.4.
Output
5.
Reading CSV Files Using the fs Module
5.1.
Steps to Read CSV Files
5.2.
Code
5.3.
JavaScript
5.4.
Output
6.
Frequently Asked Questions
6.1.
Why are CSV files used?
6.2.
How can we handle the asynchronous nature of file reading?
6.3.
Can we use external libraries for CSV parsing?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

How to Read *.CSV File in JavaScript?

Author Gaurav Gandhi
0 upvote

Introduction

Have you ever wondered how websites with such large users handle and manage data? Well, most of the time, they use CSV files to store large data. These files help organize data like tables and lists, and they're easy to use for sharing data between different programs. Now, if you're curious about how to work with these CSV files using JavaScript, we have got you covered!

How to Read *.CSV File in JavaScript

In this article, we are going to learn about CSV files and various methods to read CSV files in JavaScript.

What are CSV files?

CSV or Comma-Separated Values Files are like a table of information that you can create and open with a basic text editor or spreadsheet software like Excel. It's called "Comma-Separated Values" because the data in the table is separated by commas (or other characters like semicolons or tabs). They contain data in a well-structured format, hence making it easy for us to retrieve and understand data.

CSV files are typically used to store tabular data, where each row represents a record, and each column contains a specific data field or attribute. For example, you might have a CSV file with columns for "Name", "Roll Number", "Course", etc.
 

There are different ways to read CSV files in JavaScript. Let’s discuss them one by one.

Reading CSV Files Using csv-parse

csv-parse is a Node.js library for parsing CSV files. It helps us to read CSV data from files and convert it into JavaScript objects or arrays, which makes it easier for manipulation and processing. It contains various different options to specify the delimiter, manage header rows, etc.

Steps to Read CSV Files

Follow the given steps to read CSV files using csv-parse:

  • Install the library: We first need to install the csv-parse library by using npm ( node package manager ).
     
  • Import the parse function: Next, we need to import the parse function from the csv-parse library. This can be done by using the require method.
     
  • Specify the path: Create a variable path, and specify the path of the CSV file that we will use to read data from.
     
  • Create a read stream: We will create the read stream using fs.createReadStream(path) to read the contents of the file in the chunks and send it to the pipeline. 
     
  • Parse the CSV data: Now, we will pipe the stream through the parse function and can specify various options like

    • delimiter: specifies that a comma is used as the delimiter in our CSV file.
       
    • from_line: used to specify the line from which we want to start parsing. 
       
  • Attach the event handlers: Create the following event handlers to the parse stream:
     
    • .on("data", function (row)): executed for each row of data that is parsed. It logs each row to the console.
       
    • .on("error", function (error)): handles any errors that occur during parsing and logs the error message.
       
    • .on("end", function ()): executed when parsing is complete and logs the message provided by us.
       

Code

  • JavaScript

JavaScript

const { parse } = require("csv-parse");
const fs = require("fs");

// specify the path of the CSV file
const path = "./StudentsData.csv";

// Create a readstream
// Parse options: delimiter and start from line 1

fs.createReadStream(path)
.pipe(parse({ delimiter: ",", from_line: 1 }))
.on("data", function (row) {
// executed for each row of data
console.log(row);
})
.on("error", function (error) {
// Handle the errors
console.log(error.message);
})
.on("end", function () {
// executed when parsing is complete
console.log("File read successful");
});
You can also try this code with Online Javascript Compiler
Run Code

Output

Output

Reading CSV Files Using Node.js Native Module

We can read the CSV files in JavaScript using Node.js without any external libraries or modules, this can be done by using the built-in fs (file system) module for reading files and the readline module for processing lines.

Steps to Read CSV Files

Follow the given steps to read CSV files using the node.js native module:

  • Import the modules: We first need to import the fs and readline modules in our javascript code. 
     
  • Specify the path: Create a variable path and specify the path of the CSV file that we will use to read data from.
     
  • Create a read stream: Create a read stream using fs.createReadStream for the CSV file.
     
  • Create a readline interface: Create a readline interface to read lines from the file, specifying the input as the readStream. 
     
  • Initialize an output array: Create an array for storing the parsed CSV data.
     
  • Attach the event handlers: Create the following event handlers:

    • readInterface.on("line", ...): It is called for each line in the CSV file. It splits each line using a comma as the delimiter and adds it as an array to the output array.
       
    • readInterface.on("close", ...): It is called when the end of the file is reached. The entire file data is now read in the output.
       
    • readInterface.on("error", ...): It handles the errors and logs an error message.
       

Code

  • JavaScript

JavaScript

const fs = require("fs");
const readline = require("readline");

// specify the path of the CSV file
const path = "StudentsData.csv";

// Create a read stream
const readStream = fs.createReadStream(path);

// Create a readline interface
const readInterface = readline.createInterface({
input: readStream
});

// Initialize an array to store the parsed data
const output = [];

// Event handler for reading lines
readInterface.on("line", (line) => {
const row = line.split(",");
output.push(row);
});

// Event handler for the end of file
readInterface.on("close", () => {
console.log(output);
});

// Event handler for handling errors
readInterface.on("error", (err) => {
console.error("Error reading the CSV file:", err);
});
You can also try this code with Online Javascript Compiler
Run Code

Output

Output

Reading CSV Files Using the fs Module

The fs module in Node.js stands for "File System" and is a built-in module that provides functions for working with the file system, allowing us to perform various file-related operations. We can read the CSV files using the fs Module.

Steps to Read CSV Files

Follow the given steps to read CSV files using the fs module:

  • Import the module: We first need to import the fs module in our javascript code. 
     
  • Specify the path: Create a variable path and specify the path of the CSV file that we will use to read data from.
     
  • Read the CSV file: We can use the fs.readFile to read the CSV file. It contains a callback function, which is called when the file reading is completed or when an error occurs.
     
  • Split the data: Split the CSV data into lines using data.split("\n"). Each line in the CSV file represents a record.
     
  • Initialize an output array: Create an array for storing the parsed CSV data.
     
  • Process the file: Loop through each line using lines.forEach(). For each line, split it into fields using the line.split(","), and push the array of fields into the output array.
     
  • Log the output: The output contains the entire CSV data in the form of a 2-D array. Log the output to show it on screen.
     

Code

  • JavaScript

JavaScript

// Include the fs module
const fs = require("fs");

// Specify the path of the CSV file
const path = "StudentsData.csv";

// Read the CSV file
fs.readFile(path, "utf8", (err, data) => {
if (err) {
console.error("Error while reading:", err);
return;
}

// Split the data into lines
const lines = data.split("\n");

// Initialize the output array
const output = [];

// Loop through each line and split it into fields
lines.forEach((line) => {
const fields = line.split(",");
output.push(fields);
});

// Log the output array
console.log(output);
});
You can also try this code with Online Javascript Compiler
Run Code

Output

Output

Frequently Asked Questions

Why are CSV files used?

CSV files are largely used for storing and exchanging tabular data. CSV files are often used in various contexts for data storage, data exchange, and data manipulation due to their simplicity and compatibility with many applications.

How can we handle the asynchronous nature of file reading?

We can attach an event listener to the onload event of the FileReader object to handle the file reading completion and data processing.

Can we use external libraries for CSV parsing?

Yes, there are libraries like PapaParse and CSV-parser that simplify CSV parsing in JavaScript by providing more advanced features and error handling.

Also read about:   jquery ajax

Conclusion

In this article, we discussed, in brief, what CSV files are and how we can read data from them with JavaScript. We have learnt various methods of doing the same, which include reading data using csv-parse, node.js native module, and the fs module. 

To learn more about JavaScript, you can read these articles.

 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

We wish you Good Luck! 

Happy Learning!

Live masterclass