Vinod Vinod - 1 month ago 6
Javascript Question

Create a .txt file by converting array value as table

I have an array of

myarray = ["ram", "ram", "jan", "jan", "feb", "feb"]


Is it possible to create a .txt file which will have this value in a table format?

Answer

Frontend:

If your code is going to be on the frontend (browser), you can use the following:

var row_width = 40;

var content = "";
content += "Username" + new Array(row_width + 1).join(" ") + "Password\n";
content += "********" + new Array(row_width + 1).join(" ") + "********\n";

for (var i = 0; i < myarray.length; i += 2) {
    content += myarray[i] + new Array(row_width - myarray[i].length + 9).join(" ");
    content += myarray[i+1];
    content += "\n";
}

// Build a data URI:
uri = "data:application/octet-stream," + encodeURIComponent(content);

// Click on the file to download
// You can also do this as a button that has the href pointing to the data URI
location.href = uri;

Here's a link to a working frontend example: Fiddle

Name the file as something.txt.

Backend:

If you want to use Node.js on the backend to generate and save this file, you need to use the following:

After looping through the array and creating the 'content' string as above, you save the file as follows:

var fs = require('fs');

fs.writeFile("/path_to_file/table.txt", content, function (err){
    if (err) {
        console.log(err);
    } else {
        console.log("File saved");
    }
});

I haven't tried that code yet, but feel free to let me know if it works for you. I hope that's what you need.

NOTE that the frontend code might not be supported by some outdated/bad browsers

Comments