How to Read Data from CSV Files in Node Js App

A comprehensive guide that will help you learn how to eloquently read content from a CSV file in the Node js application using an external dependency.

There are plenty of packages available on the npm registry that can help you extract data from a CSV file.

Among all those notable packages, we chose to use the fast-csv module to pull out data from a CSV file in a node app.

Fast-csv is a top-notch library for parsing and formatting CSVs or any other delimited value file in a node.

This guide will elaborate on how to use fast csv to read data quickly yet profoundly.

Before we start developing a node app with csv read functionality, let me introduce you to the Fast csv features.

  • CSV Parsing
  • CSV Formatting
  • Built using typescript.
  • Flexible formatting and parsing options to fit almost any scenario.
  • Battle-tested in production, parsing, and formatting millions of records every day.
  • Built with streams first to avoid creating a large memory footprint when parsing large files.

Node Js Get Content FROM CSV Files Example

  • Step 1: Make Project Folder
  • Step 2: Run NPM Init
  • Step 3: Formulate Server File
  • Step 4: Install Fast CSV Package
  • Step 5: Read CSV Data
  • Step 6: Run Node Command

Make Project Folder

Run the following command to create the new folder.

mkdir node-csv

Get inside the project folder.

cd node-csv

Run NPM Init

On the terminal, type the npm command to create the package.json file.

npm init

Formulate Server File

You have to create the server.js file in your project folder.

After creating the server.js file add it into the scripts array, update the given code into the package.json’s file.


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

Install Fast CSV Package

In this step, you have to install the fast csv module in node app.

npm install fast-csv

Read CSV Data

Let us create the recovery-code.csv file and add the given data into the file.

Firstname,Lastname,Department,Location
Rachel,Booker,Sales,Manchester
Laura,Grey,Depot,London
Craig,Johnson,Depot,London
Mary,Jenkins,Engineering,Manchester
Smith,Engineering,Depot,Manchester

To get the data from the csv file add the given code into the server.js file.

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

const extractCsvData = (csvFilePath) => {
  const dataStream = fs.createReadStream(csvFilePath)
  const data = []
  dataStream
    .pipe(fastCsv.parse())
    .on('data', (row) => {
      data.push(row)
      console.log('First name:', row[0])
      console.log('Last name:', row[1])
      console.log('Department:', row[2])
      console.log('Location:', row[3])
      console.log('\n')
    })
    .on('end', (rowCount) => {
      console.log(`${rowCount} rows parsed!`)
      console.log(data)
    })
    .on('error', (error) => console.error(error))
}

const csvFile = path.resolve(__dirname, 'recovery-code.csv')
extractCsvData(csvFile)

Run Node Command

Let’s print the csv data onto the console using the given command.

node server.js

Here is the output will appear on the console screen.

First name: Firstname
Last name: Lastname
Department: Department
Location: Location


First name: Rachel
Last name: Booker
Department: Sales
Location: Manchester


First name: Laura
Last name: Grey
Department: Depot
Location: London


First name: Craig
Last name: Johnson
Department: Depot
Location: London


First name: Mary
Last name: Jenkins
Department: Engineering
Location: Manchester


First name: Smith
Last name: Engineering
Department: Depot
Location: Manchester


6 rows parsed!
[
  [ 'Firstname', 'Lastname', 'Department', 'Location' ],
  [ 'Rachel', 'Booker', 'Sales', 'Manchester' ],
  [ 'Laura', 'Grey', 'Depot', 'London' ],
  [ 'Craig', 'Johnson', 'Depot', 'London' ],
  [ 'Mary', 'Jenkins', 'Engineering', 'Manchester' ],
  [ 'Smith', 'Engineering', 'Depot', 'Manchester' ]
]

Summary

How to Read Data from CSV Files in Node Js App

In this introductory tutorial, we kept things simple as much as possible.

We learned how to simply install fast csv in node and, most importantly, parse the csv data in node without any complication.

We used a basic csv file to pour some data into it and showed that you can use the more advanced csv file on the terminal window similarly to extract the data.