Reputation: 79
I am writing a script in JS that needs to write data into files. The code I am using looks like this:
let outputContent = "data:text/csv;charset=utf-8," +
subgroupsInputData.map(e => e.join(",")).join("\n");
var outputFile = encodeURI(outputContent);
var link = document.createElement("a");
link.setAttribute("href", outputFile);
link.setAttribute("download", "input_data.csv");
document.body.appendChild(link);
link.click();
The problem is this needs to be done at least three times now. There's three different arrays that needs to be written to three different files at three different points of the script. So, I am repeating the same things in the code. I thought to put this into a function, but I have been unable to find a good way to do it. The data is in three different arrays and needs to output to three different files.
Upvotes: 1
Views: 74
Reputation: 79
I wanted to close this question, so I'm posting the solution that worked:
function writeToFile(userData, userFile) {
console.log(userData);
let outputContent = "data:text/csv;charset=utf-8," +
userData.map(e => e.join(",")).join("\n");
let outputFile = encodeURI(outputContent);
let link = document.createElement("a");
link.setAttribute("href", outputFile);
link.setAttribute("download", userFile);
document.body.appendChild(link);
link.click();
}
Thanks!
Upvotes: 0
Reputation: 4539
Below is the sample function code. you can use it. But you have to write some basic validation as per your need.
function (filename) {
const outputContent = "data:text/csv;charset=utf-8," + subgroupsInputData.map(e => e.join(",")).join("\n");
const outputFile = encodeURI(outputContent);
// Create download link
const link = document.createElement("a");
link.setAttribute("href", outputFile);
link.setAttribute("download", filename);
// Add to DOM and trigger download
document.body.appendChild(link);
link.click();
}
Upvotes: 1
Reputation: 3875
When it comes to serializing data using an existing standard, such as CSV, there is one golden rule you should always rely on- never write your own code. Supporting all of the different edgecases, incompatibilities, and reader implementations will end up devouring all of your time and will take you away from your actual project.
There's a library for this, which you should really consider using.
Upvotes: 1