Node.js Express Download CSV File From Array of Objects Using objects-to-csv Library Full Tutorial

Node.js Express Download CSV File From Array of Objects Using objects-to-csv Library Full Tutorial

 

Welcome folks today in this tutorial we will be looking how to convert array of objects to csv file and download it inside our express application. All the source code of the application is given below. A step by step youtube video is also given below.

 

 

 

Get Started

 

In order to get started you need to install these dependencies which are listed below

  1. Express is our Server
  2. objects-to-csv is the library which will convert array of objects to a csv file
  3. fs is the built in node.js module which will be responsible for deleting the file once it is downloaded inside the express app.

 

npm i express objects-to-csv

 

 

Source Code

 

index.js

 

const express = require('express')

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

const fs = require("fs")

const app = express()


var data = [
    {code: 'CA', name: 'California'},
    {code: 'TX', name: 'Texas'},
    {code: 'NY', name: 'New York'},
  ];

const PORT = process.env.PORT || 5000

app.get('/',async(req,res) => {
    const csv = new objectstocsv(data);
 
  // Save to file:
  await csv.toDisk('./test.csv');
 


  res.download("./test.csv",() => {

    fs.unlinkSync("./test.csv")

  })
})


app.listen(PORT,() => {
    console.log("app is listening on port 5000")
})

 

See also  HTML2PDF.js Adding Page Break inside PDF Document in Javascript Full Example With Source Code 2021

 

 

 

 

 

Leave a Reply