Welcome folks today in this blog post we will be parsing & reading csv files
and display data in html5 table
in browser using node.js and express
using csv-parse library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to initialize a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i csv-parse
And after that you need to make an app.js
file and copy paste the following code
app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const csv = require("csv-parse"); const fs = require("fs"); const express = require('express') const app = express() app.get("/", (req, res) => { }); app.listen(5000,() => { console.log("App is listening on port 5000") }) |
As you can see we are importing all the libraries
at the top and we started the express app at the port number 5000. And now we are having a /
route inside which we will be reading
the content of the csv
file and displaying it inside the html5 table
in the browser. For this we are including the csv-parse
library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
app.get("/", (req, res) => { fs.readFile("./data.csv", "utf-8", (err, data) => { if (err) { console.log(err); } else { csv.parse(data, { columns: true }, (err, rows) => { if (err) { console.log(err); } else { let html = "<table>"; rows.forEach((row) => { html += "<tr>"; for (const key in row) { html += `<td>${row[key]}</td>`; } html += "</tr>"; }); html += "</table>"; res.send(html); } }); } }); }); |
As you can see we are reading the data.csv
file using the fs
module of node.js. And then we are using the csv-parse
module and inside it we are using the parse()
method to read the contents of the csv
file and then we are passing the columns
option to be true. And then inside the callback function we are displaying the content
of the csv file inside the html5 table. And then we are rendering the dynamic
table html and returning that html
response back to the browser as shown below
Now to run this express
app you need to create the data.csv
file inside the root directory and copy paste the following code
data.csv
1 2 3 |
Name,Age,Country John,23,New Zealand Adam,54,Australia |
Now to run the express
app using the below command as shown below
nodemon index.js