How to read CSV files in Node.js

Read CSV files in Node.js :

CSV files are used to store data in tabular format. CSV stands for Comma Separated Values.

As it is used to store data in tabular format, its fields are separated by a comma and each row is separated with a new line. csv is a widely used format and many application supports export to CSV. For example, you can export an excel file in CSV format. You can even create one CSV file using any popular text editor. Create one text file and save it as .csv with the values of each row separated by a comma.

Reading CSV files in Node.js :

The file system module or fs module is used to read CSV files.

For parsing we will use one npm module called csv-parser :

npm i csv-parser

Create one content.csv file in the same folder with the following content :


Create one index.js file to read the content of this CSV file :

const csv = require("csv-parser");
const fs = require("fs");
const final_result = [];

  .on("data", data => final_result.push(data))
  .on("end", () => {

Run this file using node and it will print the value of final_result as like below :

  { Name: 'Alex', Age: '12', Marks: '44' },
  { Name: 'Bob', Age: '14', Marks: '55' },
  { Name: 'Eliza', Age: '13', Marks: '60' }

It is an array of JSON objects. We can easily get the value of each row item.