How to Export CSV Files in Node.js using json2csv

In my journey through the dynamic realm of data-driven applications, I've frequently encountered the need to export data in various formats, notably CSV (Comma-Separated Values). Whether I'm crafting a reporting system, developing a data extraction tool, or simply sharing data with others, having an efficient method to export data to CSV has proven indispensable.

In this guide, I'll delve into how I effortlessly achieved this task in Node.js, thanks to the versatile json2csv library. With its user-friendly approach and adaptability, json2csv has become a valuable asset in my toolkit, allowing me to effortlessly convert JSON data into CSV format.

Join me as I walk you through the entire process, from installation to the creation of CSV files, and discover how this library can simplify data export in your Node.js applications.

Step 1: Create Node Express js App

In this tutorial, we'll start by creating a Node.js application using the Express.js framework. Express.js is a popular web application framework for Node.js that simplifies building web servers and APIs.

Prerequisites:

  • Node.js is installed on your machine. If not, download it from nodejs.org.

Let's get started:

Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following commands.

mkdir export-csv-app
cd export-csv-app
npm init -y

 

Step 2: Connect the App to the Database

In this step, we'll connect your Node.js Express application to a MySQL database. This connection allows your application to interact with the database, enabling data storage and retrieval. Follow these steps to set up the database connection.

npm install mysql --save

In your Node.js Express application, create a new JavaScript file (e.g., database.js) to handle the database connection. Inside this file, configure the connection settings using the MySQL driver 

// database.js

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',       // Your MySQL host
  user: 'your_username',    // Your MySQL username
  password: 'your_password', // Your MySQL password
  database: 'your_database' // Your MySQL database name
});

// Connect to the MySQL database
connection.connect((err) => {
  if (err) {
    console.error('Error connecting to MySQL:', err);
    return;
  }
  console.log('Connected to MySQL database');
});

module.exports = connection;

 

Step 3: Install express and required Modules

It seems like you want to install several Node.js packages as dependencies for your project using npm. You can install them with the following command.

npm install express mysql body-parser json2csv --save

Here's what each package does:

  • express: This package is the Express.js web framework, which is used to build web applications and APIs.

  • mysql: This package provides the MySQL database driver for Node.js, allowing your application to connect to and interact with MySQL databases.

  • body-parser: This package is used to parse incoming request bodies in your Express application, which is often necessary when dealing with form data or JSON payloads.

  • json2csv: This package is used to convert JSON data into CSV format, which is handy for exporting data to CSV files.

 

Step 4: Create Server.js File

You can create a server.js file and import the required Node.js packages like Express, Express Validator, MySQL, body-parser, JSON Web Token (jsonwebtoken), bcryptjs, and cors 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

Run the following command.

nodemon server.js

 

Conclusion

You've learned how to export data as a CSV file in a Node.js application using the json2csv library. This process can be adapted to export data from databases, APIs, or any other data source in your Node.js projects, making it a valuable tool for handling CSV exports.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS