Welcome folks today in this blog post we will be generating and downloading csv file
with headers using csv-express
middleware in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command
npm init -y
npm i express
npm i csv-express
And after that you will see the below directory
structure of the node.js and express as shown below
Now we need to make the index.js
file and copy paste the below code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var express = require('express') var csv = require('csv-express') var app = express() // Basic app.get('/', function(req, res) { res.csv([ ["a", "b", "c"] , ["d", "e", "f"] ]) }) // Add headers app.get('/headers', function(req, res) { res.csv([ {"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6} ], true) }) app.listen(3000) |
As you can see we are importing the csv-express
middleware and then we are passing the csv
middleware when we go to the /
route and then as soon as we go to that route the csv
file is downloaded as an attachment and then if we need the csv file with headers
then we need to go to /headers
route and then the csv file will be downloaded as an attachment.