How to write a CSV file using Node.js

Quick tutorial to write data array to CSV file using Node.js

You can use a great library to quickly write object arrays to CSV files using Node.js, which isobjects-to-csv.

Of course, there are many other libraries. I found this to be useful for one of my projects because I had to generate a one-time CSV file, so I wrote this little tutorial.

Use onestreamLibrary-basedfast-csvIt may meet your needs in more performance-oriented applications.

Install it using the following command:

npm install objects-to-csv

Then require it in your Node.js code:

const ObjectsToCsv = require('objects-to-csv')

When you are ready to write the CSV object array, initialize a new ObjectsToCsv object instance:

const csv = new ObjectsToCsv(list)

Then callcsv.toDisk(), Pass the file you want to write (relative to the base path of your application):

await csv.toDisk('./list.csv')

This is a promise-based API, I usedawait, So you need toAsynchronousFeatures.

The column names in the CSV are automatically inferred from the object attribute names.

Please note that this command will overwrite the existing contents of the file. To attach to the file, useappendThe property is set to true:

await csv.toDisk('./list.csv', { append: true })

Download mine for freeNode.js manual

More node tutorials: