How to Reading and Writing CSV File in Node.js?

01-Sep-2022

.

Admin

How to Reading and Writing CSV File in Node.js?

Hi Dev,

This is a short guide on how to reading and writing csv file in node.js. this example will help you reading and writing csv file in nodejs. This post will give you simple example of reading and writing csv file in node js example. it's simple example of nodejs reading and writing csv file. So, let's follow few step to create example of node.js reading and writing csv file example.

In this tutorial, we learn to reading and writing csv file in nodejs using Node FS (File System) built-in module and csv-parse. While you can read CSV files using the fs module that comes with Node and get the content of the file. In this example read csv file using csv-parser packages.

So let's start following example with output:

Create Node.js Project


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Installing node-csv

The module consists of csv-generate, csv-parse, csv-transform and csv-stringify packages.

npm install csv

Example 1: Reading CSV File with csv-parse

Read CSV files, we’ll be using the csv-parse package from node-csv.

Let's create a file, called index.js and construct a parser:

index.js

// call package read CSV file

var fs = require('fs');

var { parse } = require("csv-parse");

// call read CSV file

var parser = parse({columns: true}, function (err, records) {

console.log(records);

});

// get CSV file path

fs.createReadStream(__dirname+'/demo.csv').pipe(parser);

Output:

[

{ Name: 'Piyush Kamani', Designation: 'Web Developer', Year: '2017' },

{ Name: 'Vivek Thummar', Designation: 'Web Developer', Year: '2022' },

{ Name: 'Yesh Kamani', Designation: 'Web Developer', Year: '2022' }

]

Example 2: Writing CSV Files Using the fs module

index.js

// call package fs (File System)

var fs = require('fs');

// write data to print CSV file

const data = `

Name,Designation,Year

Piyush Kamani,Web Developer,2017

Vivek Thummar,Web Developer,2022

Yesh Kamani,Web Developer,2022

`;

// Print data to print CSV file

fs.writeFile("demo.csv", data, "utf-8", (err) => {

if (err) console.log(err);

else console.log("Data saved");

});

Output:

demo.csv

Name,Designation,Year

Piyush Kamani,Web Developer,2017

Vivek Thummar,Web Developer,2022

Yesh Kamani,Web Developer,2022

I hope it can help you...

#Node JS