Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





How to Export and Download CSV From MySQL Database?

Create a Project

c:\> npx express --view=ejs crud_api

Initialise and Configure Our Project

File Name :

c:\crud_api> npm init -y

npm install

c:\crud_api> npm install

Install express and other dependencies

File Name :

c:\crud_api> npm install express --save

install Body Parser :-

File Name :

c:\crud_api> npm install body-parser --save

MySql Install

File Name :

c:\crud_api> npm install mysql --save

Nodemon Install

File Name :

c:\crud_api> npm install --save-dev nodemon

Nodemon Install

File Name :

npm install json2csv --save

Create Database Connection

File Name : database.js

var mysql = require('mysql');
var conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'nodedb'
});
conn.connect(function(err) {
if (err) throw err;
console.log('Database is connected successfully !');
});
module.exports = conn;

create server.js

File Name : server.js

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;

File Name :

nodemon server.js
after run this command open your browser and hit
http://127.0.0.1:3000/export-csv





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here