Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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 suit your needs for 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, create a new ObjectsToCsv 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 property 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 })