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:");
// 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