How to read a CSV file with Node.js
By Flavio Copes
Learn how to read a CSV file with Node.js using the neat-csv package, which wraps csv-parser in a simple async/await interface returning an array of objects.
To read a CSV file with Node.js you can use the neat-csv package: read the file, pass its content to neatCsv(), and you get back an array of JavaScript objects, one per row.
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')
Say we have an orders.csv file with this content:
product,price,quantity
espresso machine,250,1
coffee beans,12,4
The first line holds the column names. Every following line is a row of data.
Load the CSV from the filesystem and invoke neatCsv passing the content of the file:
const fs = require('fs')
fs.readFile('./orders.csv', async (err, data) => {
if (err) {
console.error(err)
return
}
console.log(await neatCsv(data))
})
Here’s what it prints:
[
{ product: 'espresso machine', price: '250', quantity: '1' },
{ product: 'coffee beans', price: '12', quantity: '4' }
]
Each row became an object, and the header line provided the property names. Now you can start doing whatever you need to do with the data, which is formatted as a JavaScript array of objects.
Notice one detail in the output: every value is a string, including the numbers. CSV has no types. If you need to sum prices or compare quantities, convert them first, for example with Number(order.price).
What if the file uses semicolons?
Some CSV files, especially ones exported from European spreadsheets, separate values with ; instead of ,. You can pass options as the second argument, and they are handed over to csv-parser:
const orders = await neatCsv(data, { separator: ';' })
A note on require and newer versions
Recent versions of neat-csv are published as ES modules. If require() fails for you with an ERR_REQUIRE_ESM error, you have two options: load it with import neatCsv from 'neat-csv' in an ES module, or install the older CommonJS line with npm install neat-csv@5. The API shown here works the same in both.
If you need to convert that array to JSON or back to CSV without writing a script, I built a free JSON ↔ CSV converter for quick one-off jobs.
Related posts about node: