Skip to content

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 })

→ Get my Node.js Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, 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

Bootcamp 2025

Join the waiting list