How to Write CSV File Data in Node JS?

02-Sep-2022

.

Admin

How to Write CSV File Data in Node JS?

Hi Dev,

Now, let's see the article on how to write CSV file data in node js. This post will give you a simple example of how to write CSV file data in nodejs. I would like to show you the write CSV file in nodejs. we will help you to give an example of write CSV file in node js example.

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

So let's start following example with output:

Step 1: 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

Step 2: Installing node-csv

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

npm install csv

Write CSV File with csv-parse

write 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:

Step 3: Update index.js file

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