In this tutorial, we will learn how to write an array of data to a CSV file using Node.js. We will be using the objects-to-csv
library, which is a great tool for quickly writing an array of objects to a CSV file.
To get started, let’s install the objects-to-csv
library by running the following command in your Node.js project folder:
npm install objects-to-csv
Once the library is installed, we can require it in our Node.js code like this:
const ObjectsToCsv = require('objects-to-csv');
Next, we need to initialize a new ObjectsToCsv object instance by passing our array of objects to it:
const csv = new ObjectsToCsv(list);
Make sure list
is the array containing the data you want to write to the CSV file.
To write the data to disk and create the CSV file, we can use the toDisk()
method of the csv
object. This method takes the file path as its parameter, relative to your application’s base path:
await csv.toDisk('./list.csv');
Please note that we are using the await
keyword because this method returns a promise. You need to call this code inside an async function.
By default, the column names in the CSV file are automatically inferred from the object property names.
If you want to append to an existing CSV file instead of overwriting it, you can pass a second object with the append
property set to true. Here’s an example:
await csv.toDisk('./list.csv', { append: true });
That’s it! Now you know how to write a CSV file with Node.js using the objects-to-csv
library.