How to write a CSV file with Node.js
A quick tutorial to write an array of data to a CSV file using Node.js
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 })
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025