Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created December 18, 2019 17:00
Show Gist options
  • Save okovalov/0c0f24d4bf627565cec526f3d8342b94 to your computer and use it in GitHub Desktop.
Save okovalov/0c0f24d4bf627565cec526f3d8342b94 to your computer and use it in GitHub Desktop.
Read:
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.
Write:
A great library you can use to quickly write an array of objects to a CSV file using Node.js is objects-to-csv.
Many other libraries exist, of course. I found this useful for a project of mine where I had to generate a one-time CSV file, so I wrote this little tutorial.
Using a stream-based library like fast-csv might suits your needs in more performance-oriented applications.
Install it using:
npm install objects-to-csv
then require it in your Node.js code:
const ObjectsToCsv = require('objects-to-csv')
When you have an array of objects ready to write to CSV, initialize a new ObjectsToCsv object instance:
const csv = new ObjectsToCsv(list)
then call csv.toDisk(), passing the file you want to write to (relative to your app base path):
await csv.toDisk('./list.csv')
This is a promise-based API and I used await, so you need to call this inside an async function.
The column names in the CSV are automatically inferred from the object properties names.
Note that this command overwrites the existing content of the file. To append to that file, pass a second object with the append property set to true:
await csv.toDisk('./list.csv', { append: true })
https://flaviocopes.com/node-write-csv/
https://flaviocopes.com/node-read-csv/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment