Node Js Extract Content From CSV Files Tutorial

Last Updated on by in Node JS

CSV files are best for gathering the data in a text file for multiple uses in web development.

This quick post will reveal how to work with CSV files in Node js; throughout this tutorial, we will show you how to read a csv file in node js using a fast csv package.

We will not just use the fast-csv module to read contents from a csv file. Instead, we will also use the node’s default fs and path modules for extracting csv file data.

We will start with creating a basic csv file and conjugate all the modules and files to read the csv file data line by line. At the end of this tutorial, you will have a better understanding of parsing the csv file in node.

How to Get Content from CSV File in Node using Fast CSV

  • Step 1: Create Node Project
  • Step 2: Build App.js File
  • Step 3: Add Fast CSV Module
  • Step 4: Create Sample CSV File
  • Step 5: Read CSV Content
  • Step 6: Show CSV Data

Create Node Project

Move to console, type the given command and then execute the command to make the project folder.

mkdir node-demo

Let’s jump into the folder.

cd node-demo

While staying in the app folder, run the npm command. This command will create the package.json file, that contains information about your project.

npm init

Build App.js File

In your app folder, you have to create a new app.js file, in this file we will write the code to handle the functionality.

Let us also, add the command in script array, make sure to open the package.json’s file and add the command as suggested below.


...
...
...
"scripts": {
   "start": "node app.js"
},
...
...
...

Add Fast CSV Module

Now, we need to install the fast csv package in our node app, ensure that you execute the provided command from the terminal.

npm install fast-csv

Create Sample CSV File

In this step, you will be creating a sample csv file so make sure to create users.csv file at the root of your node project.

Thereafter insert the following data into the file.

Name,Email,City
Leanne Graham,sincere@april.biz,Gwenborough
Ervin Howell,shanna@melissa.tv,Wisokyburgh
Clementine Bauch,nathan@yesenia.net,McKenziehaven
Patricia Lebsack,julianne.OConner@kory.org,South Elvis
Chelsey Dietrich,lucio_Hettinger@annie.ca,Roscoeview

Read CSV Content

Make sure to import the fs, path and fast-csv module at the topmost section of the file.

Create a function that takes a URL or path of the csv file; this function process the csv file and allows you to print the csv content on the terminal screen.

Therefore, open the app.js file, now copy all the code line by line inside this file.

const fs = require('fs')
const path = require('path')
const fastCsv = require('fast-csv')

const readCSV = (csvFilePath) => {
  const readData = fs.createReadStream(csvFilePath)
  const data = []
  readData
    .pipe(fastCsv.parse())
    .on('data', (row) => {
      data.push(row)
      console.log('Name:', row[0])
      console.log('Email:', row[1])
      console.log('City:', row[2])
      console.log('\n')
    })
    .on('end', (rowCount) => {
      console.log(`${rowCount} rows parsed!`)
      console.log(data)
    })
    .on('error', (e) => console.error(e))
}

const pathCsv = path.resolve(__dirname, 'users.csv')
readCSV(pathCsv)

Show CSV Data

Head over to terminal, on the console type the given command then press enter to display the csv data.

node app.js

Node Js Extract Content From CSV Files Tutorial

Conclusion

A CSV file stands for comma-separated values, and it is widely used to gather information or data in a comma-separated format within the text file.

You ideally take the help of a CSV file to transfer data between programs that cannot swap data.

CSV files are typically used or located in spreadsheets and databases.

In this simple, short and descriptive guide, we elaborated step by step on how to read data from a csv file in a node js application using a third party npm module.