Skip to content

How to read a CSV file with Node.js

A quick tutorial to read data from a CSV file using Node.js

Many different npm modules let you read from a CSV file.

Most of them are based on streams, like csv-parser or node-csv.

Those are great to deal with CSV in a production system.

I like to keep things simple when I don't have performance in mind. For example, for a one-time parsing of CSV that I had to do to consolidate my backend systems.

To do so, I used neat-csv, a package that exposes the csv-parser functionality to a simple async/await interface.

Install it using npm install neat-csv and require it in your app:

const neatCsv = require('neat-csv');

then load the CSV from the filesystem and invoke neatCsv passing the content of the file:

const fs = require('fs')

fs.readFile('./file.csv', async (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(await neatCsv(data))
})

Now you can start doing whatever you need to do with the data, which is formatted as a JavaScript array of objects.

→ Download my free Node.js Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about node: