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"?

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Make sure to add encodeURIComponent(tsv) so tabs are not stripped away
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!

2 Comments

Why do you set download attribute value to .txt if requirement is to create a text/tab-separated-values file?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.