How to read CSV file in nodeJS

Share the post

Hello All, Today we will start a new topic called nodeJS. In this nodeJS tutorial, We will discuss How to read CSV file in nodeJS.

This will be a simple example where we create a new nodeJS project with an assets folder that will contain a CSV file. So, this CSV file will be stored locally. After that, We will fetch the data from that CSV file using npm dependency called csv.

So, let’s start…

Steps for How to read CSV file in nodeJS

We will follow the below steps to read the CSV file

  • Create a new nodeJS application
  • Install csv npm dependency in nodeJS application
  • Copy CSV file in the assets folder
  • Create & Write logic in app.js
  • Edit Package.json & Run Node Application

  • Create a new nodeJS application
  • Create a new folder in your favorite drive called ‘node‘. Open a command prompt at this folder location. Now, We will write the following command to get package.json

    npm init
    

    That command will help us to generate package.json which contains project information.

  • Install csv npm dependency in nodeJS application
  • Now, We will install csv dependency using the following command

    npm i csv
    

  • Copy CSV file in the assets folder
  • Create a new folder called ‘assets‘ in the root folder. Then, copy the below students.csv file into the assets folder.

    Ramesh,1,10
    Suresh,2,10
    Rajesh,3,10
    Nilesh,4,10
    Dharmesh,5,10
    

  • Create & Write logic in app.js
  • Create a new file called ‘app.js‘ in the root folder. Then, Write the below logic in app.js to read the CSV file.

    const fs = require('fs');
    const csv = require('csv');
    
    const fileData = fs.createReadStream('assets/students.csv')
        .pipe(csv.parse({ delimiter: ',' })
            .on('data', (row) => {
                console.log('Name:', row[0]);
                console.log('Roll Number:', row[1]);
                console.log('Class:', row[2]);
            })
            .on('error', (e) => {
                console.error('error' + e);
            }))
    
    

  • Edit Package.json & Run Node Application
  • Now, Edit the Package.json file add the below script to run the node application

    "scripts": {
        "start": "node app.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
    

    Run the Node Application using the below command

    node app.js
    

    Output

    How to read CSV file in nodeJS
    How to read CSV file in nodeJS

    Leave a Comment