5

I'm new to javascript and I wanted to know if I can export data into a txt file. I can put the data in an alert but I want it to be downloaded onto the clients system as a txt file. How do I achieve this?

MisterGeeky
  • 254
  • 1
  • 8
  • 18

2 Answers2

3

At the moment the File API: Writer is not ready, so you do not have direct interfaces to save file.

Still, you can create a link and put the text in the url.

var link = document.createElement('a');
link.href = 'data:text/plain;charset=UTF-8,' + encodeURIComponent(yourTextGoesHere);
link.innerHTML = 'Open the text file';
//set default action on link to force download, and set default filename:
link.download = 'some file name.txt';     

//now put the link somewhere in the html document:
document.body.appendChild(link);

Written by hand and not tested. Should work, but might require debugging.

Edit: added download attribute.

SWilk
  • 3,261
  • 8
  • 30
  • 51
  • Is this possible to open savefile dialog asfter generate a file? – arrowman Jan 13 '17 at 08:23
  • You can add `download="some file name.txt"` to force download the file, but most browsers will just download it, and not ask where to save the file. The FileWriter api I have mentioned here seems to be discontinued by W3C, and, while it is supported in Chrome, it might be dropped, so I would not use that. http://caniuse.com/#feat=filesystem – SWilk Jan 16 '17 at 13:28
2

Save text

function save(text){
    var link = document.createElement('a');
    link.href = 'data:text/plain;charset=UTF-8,' + escape(text);
    link.download = 'output.txt';
    link.click();
}
Explosion
  • 328
  • 2
  • 10