How to Read CSV File Data in Node JS?

Sep 02, 2022

.

Admin

How to Read CSV File Data in Node JS?

Hi Dev,

Now, let's see the article on how to read CSV file data in node js. This post will give you a simple example of how to read CSV file data in nodejs. I would like to show you the read CSV file in nodejs. we will help you to give an example of read CSV file in node js example.

In this tutorial, we learn to read CSV file in nodejs using Node FS (File System) built-in module and csv-parse. While you can read CSV files using the fs module that comes with Node and get the content of the file. In this example read CSV file using CSV-parser packages.

So let's start following example with output:

Step 1: Create Node.js Project


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Step 2: Installing node-csv

The module consists of csv-generate, csv-parse, csv-transform and csv-stringify packages.

npm install csv

Reading CSV File with csv-parse

Read CSV files, we’ll be using the csv-parse package from node-csv.

Let's create a file, called index.js and construct a parser:

Step 3: Update index.js file

index.js

// call package read CSV file

var fs = require('fs');

var { parse } = require("csv-parse");

// call read CSV file

var parser = parse({columns: true}, function (err, records) {

console.log(records);

});

// get CSV file path

fs.createReadStream(__dirname+'/demo.csv').pipe(parser);

Output:

[

{ Name: 'Piyush Kamani', Designation: 'Web Developer', Year: '2017' },

{ Name: 'Vivek Thummar', Designation: 'Web Developer', Year: '2022' },

{ Name: 'Yesh Kamani', Designation: 'Web Developer', Year: '2022' }

]

#Node JS