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:-
- Install node (
npm init -y
) - Install packages (
npm i fs
) - 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)