2

Is it possible, using javascript, to generate a TSV file on the browser side given that I have an array of headers that I want to put in the file?

For example, in my javascript I have:

var fields = ["field1", "field2", "field3", "field4", "field5"];

Can I create a TSV file which contains the following in the first line

field1      field2      field3      field4      field5

and save it as "fields.tsv"?

moja
  • 95
  • 1
  • 13

2 Answers2

3

You can use Array.prototype.join() with parameter \t or \t\t to join fields array values single or multiple tab characters; use data URI with MIME type set to text/tab-separated-values with joined array concatenated , set window.location.href or window.open() first parameter to data URI to initiate Save File dialog.

Edit, Updated

As noted by @Eugene, pass joined fileds array to encodeURIComponent() to preserve tab characters

var fields = ["field1", "field2", "field3", "field4", "field5"];
var tsv = fields.join("\t");
window.location.href = "data:text/tab-separated-values," + encodeURIComponent(tsv);

plnkr http://plnkr.co/edit/ehfbwS4UWdLiM350rx1i?p=preview

guest271314
  • 1
  • 15
  • 104
  • 177
0

Based from the suggestions and the 2nd answer on this post I have come to this plunkr solution. :)

function createFile () {
    var fields = ["field1", "field2", "field3", "field4", "field5"];
    var tsv = fields.join("\t");
    var generatedFile = makeTextFile(tsv);
    var link = document.getElementById('downloadLink');
    link.href = generatedFile;
};

Thanks for all the help!

Community
  • 1
  • 1
moja
  • 95
  • 1
  • 13
  • Why do you set `download` attribute value to `.txt` if requirement is to create a `text/tab-separated-values` file? – guest271314 May 12 '16 at 14:02
  • The `tsv` file generated will be opened via Microsoft Excel and Excel saves tab-delimited files with a `.txt` extension that's why I'm saving it as `.txt` for consistency. – moja May 13 '16 at 03:28