write to csv file in nodejs

How to Export to CSV in NodeJS

Sometimes you may need to write to CSV files in NodeJS. In this article, we will look at how to export to CSV in NodeJS.


How to Export to CSV in NodeJS

Here are the steps to export to CSV in NodeJS. We will use fast-csv node module for this purpose.


1. Install csv-writer

Open terminal and run the following command to install fast-csv.

npm install fast-csv

Also read : How to Make POST Request in cURL


2. Create NodeJS application to Export to CSV

Create a JS file for NodeJS application

$ sudo vi app.js

Add the following code to it.

const fastcsv = require("fast-csv");
const fs = require("fs");
const ws = fs.createWriteStream("data.csv");

const jsonData = [ { id: 1,
    name: 'Node.js',
    description: 'JS web applications',
    created_at: '2021-09-02' },
  { id: 2,
    name: 'Vue.js',
    description: 'for building UI',
    created_at: '2021-09-05' },
  { id: 3,
    name: 'Angular.js',
    description: 'for building mobile & desktop web app',
    created_at: '2021-09-08' } ];

fastcsv
  .write(jsonData, { headers: true })
  .on("finish", function() {
    console.log("Write to CSV successfully!");
  })
  .pipe(ws);

Let us look at the above code in details. We include fast-csv for json to csv conversion and fs module for writing csv files. jsonData contains our sample json data. We have used fs.createWriteStream function to write to csv file. You can change the file path as per your requirement.

We use write function available in fastcsv to convert json to csv and write to file. We also specify headers:true to make 1st line of csv file as headers. fascsv will generate the headers from key values in json data. We also provide pipe function to write the output to csv file.

Save and close the file.

Also read : Bash Wait Command in Linux


3. Run NodeJS app

Run the following command to run NodeJS app.

$ sudo node app.js

It will write JSON data to csv file.

$ sudo cat data.csv
id,name,description,created_at
1,Node.js,JS web applications ,2021-09-02
2,Vue.js,for building UI,2021-09-05
3,Angular.js,for building mobile & desktop web app,2021-09-08

We have learnt how to write JSON to CSV in NodeJS.

Also read : How to Convert CSV to JSON in NodeJS


Leave a Reply

Your email address will not be published. Required fields are marked *