How to export and download CSV in Node JS

Learn how to export and download CSV file in Node JS.

Video tutorial:

First, we create a folder and open the command prompt or terminal in it using the following command:

cd "path of folder"

Then you can initialize the NPM by running the following command:

npm init

Then you can install the required modules:

npm install express http fs fast-csv

We will be using express as the main module for all types of requests and responses. HTTP for starting the server, fs stands for File System, and fast-csv to create CSV files. We have created a file named “server.js”. So you can start the server by running the following command in your terminal:

nodemon server.js
# or node server.js

Create a folder named “public” in root of your Node JS folder, here we will save the CSV file. Now your “server.js” file will have the following content:

var express = require("express");
var app = express();
var http = require("http").createServer(app);
var fileSystem = require("fs");
var fastcsv = require("fast-csv");

app.use("/public", express.static(__dirname + "/public"));

http.listen(3000, function () {
    console.log("Connected");

    app.get("/exportData", function (request, result) {

        var data = [{
            "id": 1,
            "name": "Adnan",
            "age": 29
        }, {
            "id": 2,
            "name": "Ali",
            "age": 31
        }, {
            "id": 3,
            "name": "Ahmad",
            "age": 33
        }];

        var ws = fileSystem.createWriteStream("public/data.csv");
        fastcsv
            .write(data, { headers: true })
            .on("finish", function() {

                result.send("<a href='/public/data.csv' download='data.csv' id='download-link'></a><script>document.getElementById('download-link').click();</script>");
            })
            .pipe(ws);
    });
});
  1. We are first creating instances of all modules.
  2. Then we are telling the server that we will be saving files in the “public” folder.
  3. After that, we are starting the server at port 3000.
  4. Then we are creating a GET route which when accessed will create a CSV file and download it in the user’s browser.
  5. Now, we are creating an array which will be the data of CSV file. You can replace that with your own array.
  6. Then we are creating a write stream, and in that, we are sending the path of CSV file. In our case, it is in the “public” folder and named “data.csv”.
  7. Write the data array using a fast-csv module. When the writing finished, simply create an anchor tag and add an attribute “download“. Set the href to the path of file. And fire a click event using Javascript.
  8. We are using pipe() function that will add the write stream in fast-csv queue.

Explore our more tutorials and projects developed in Node JS.

[wpdm_package id=’556′]