DEV Community

Cover image for Text to CSV using Javascript (JS)
Kunal Singh
Kunal Singh

Posted on

Text to CSV using Javascript (JS)

What we will be looking at?

In this tutorial we are going to see how we can convert our data from text to csv and export it.

Steps:-

  1. Install node (npm init -y)
  2. Install packages (npm i fs)
  3. Create ont .js extension file and open it in your favorite editor.

Code Explanation

const fs = require("fs"); Here we will be importing fs which we install. It will be used for exporting the file.

Here we have a dummy text data which we will be converting to CSV.
let s =This is my file
showing some data
data1 = 12
data2 = 156;

Here we have define a function that will take care of the conversation from text to csv.
const textToCSV = () => {
// 1. Split the lines
// 2. Split each words using spaces and join them using coma(,)
// 3. Rejoin the lines
let text = s
.split("\n")
.map((line) => line.split(/\s+/).join(","))
.join("\n");
// Save the data in csv format
fs.writeFileSync("dataNew.csv", text);
// Print Task completion
console.log("Task Completed");
};

Text has been converted to csv.
textToCSV();

Whole code

`// Import module
const fs = require("fs");

// Text to be stored in csv file
let s = /This is my file
showing some data
data1 = 12
data2 = 156/
;

// Function to create text to csv
const textToCSV = () => {
// 1. Split the lines
// 2. Split each words using spaces and join them using coma(,)
// 3. Rejoin the lines
let text = s
.split("\n")
.map((line) => line.split(/\s+/).join(","))
.join("\n");
// Save the data in csv format
fs.writeFileSync("dataNew.csv", text);
// Print Task completion
console.log("Task Completed");
};

textToCSV();`

Top comments (0)