Skip to content

All topics  /  Node.js

How to Export and Download CSV in Node js?

Node.js ·

For teams turning “How to Export and Download CSV in Node js?” into a repeatable delivery task, the linked implementation guide can document setup, troubleshooting and review time; managers should interpret those records alongside reliability and completed work, not as a stand-alone score.

Package and operating-system behaviour can change, so verify the commands and supported versions through the Node.js project before running them on a production host.

Hello Friends,

This article will provide some of the most important examples of how to export and download CSV in node js. I would like to show you export and download MySQL data to a CSV files using node.js. If you want to see an example of exporting MySQL data to a CSV file using node.js then you are in the right place.

While working on a node JS project, I had the need to pull certain data from my database and represent values in a CSV file, This guide aims at simplifying the process of creating a CSV file and making it downloadable from the client side.

Step 1: Create Node Express js App


Execute the following command on the terminal to create the node js app:

mkdir myApp
cd myApp
npm init -y

Step 2: Connect App to Database

Create a database.js file into your app root directory add the following code into it to connect your node js express app to the database:

var mysql = require('mysql');
var conn = mysql.createConnection({
    host: 'localhost', // Replace with your host name
    user: 'root',      // Replace with your database username
    password: '',      // Replace with your database password
    database: 'my-node' // // Replace with your database Name
}); 

 
conn.connect(function(err) {
    if (err) throw err;
    console.log('Database is connected successfully !');
});
module.exports = conn;

Step 3: Install express and required Modules

Execute the following command on the terminal to install express express-validator MySQL body-parser JSON web token bcryptjs cors into your node js express app:

npm install express mysql body-parser json2csv --save

Express — Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

json2csv — A JSON to CSV and CSV to JSON converter that natively supports sub-documents and auto-generates the CSV heading.

MySQL — MySQL an open-source relational database management system (RDBMS).

body-parser — Express body-parser is an npm library used to process data sent through an HTTP request body. It exposes four express middlewares for parsing text, JSON, URL-encoded and raw data set through an HTTP request body.

Step 4: Create Server.js File

Create server.js file and import express express-validator MySQL body-parser JSON web token bcryptjs cors into your server.js file; as shown below:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var db = require('./database');
var Json2csvParser = require('json2csv').Parser;
const fs = require('fs');

 
var app = express();

 
app.get('/export-csv',function(req,res){
    db.query("SELECT * FROM users", function (err, users, fields) {
        if (err) throw err;
        console.log("users:");

     
        const jsonUsers = JSON.parse(JSON.stringify(users));
        console.log(jsonUsers);

 
        // -> Convert JSON to CSV data
        const csvFields = ['id', 'name', 'email'];
        const json2csvParser = new Json2csvParser({ csvFields });
        const csv = json2csvParser.parse(jsonCustomers);

 
        console.log(csv);

 
        res.setHeader("Content-Type", "text/csv");
        res.setHeader("Content-Disposition", "attachment; filename=users.csv");

 
        res.status(200).end(csv);

    
        // -> Check 'customer.csv' file in root project folder
    });
});

 
// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});

 
module.exports = app;

Step 5: Start Node Express Js App Server

Execute the following command on the terminal to start the node express js server:

//run the below command
nodemon server.js

After running this command open your browser and hit

http://127.0.0.1:3000/export-csv