Skip to content

How to write a CSV file with Node.js

New Course Coming Soon:

Get Really Good at Git

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 })
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my Node.js Handbook
→ Read my Node.js Tutorial on The Valley of Code

Here is how can I help you: