0

I have seen lots of posting about people wanting to write text files using Javascript. It looks like this used to be possible. I have tried lots and lots of the examples, but can't get any to work short of Downloadify.

I am looking for something that will let me write a text value out to a local file on my own machine. I am running the Javascript locally and not on a web server. I would like this to be written out immediately and not require pressing a Download button like Downloadify.

Are there any options?

Rob
  • 189
  • 2
  • 11
  • this question has been asked several times, you might find some useful information here: http://stackoverflow.com/questions/21012580/is-it-possible-to-write-data-to-file-using-only-javascript and here: http://stackoverflow.com/questions/585234/how-to-read-and-write-into-file-using-javascript – Alfonso Apr 12 '16 at 20:19

2 Answers2

0

you can actually use html5 local storage

localStorage.setItem(KEY, VALUE);

to set the key/value pair(s) and

var result = localStorage.getItem(KEY);

to get the value of the key

The localStorage object stores the data with no expiration date.

  • Thanks. Does localStorage object create file? Which one do I set for the file name? – Rob Apr 12 '16 at 20:23
  • I tried using: function SaveDatFileBro(localstorage) { localstorage.root.getFile("info.txt", {create: true}); } but this did not seem to work. – Rob Apr 12 '16 at 20:25
  • @Rob `localStorage` is internal to the browser. It uses files to save the data between browser executions, but the filename is chosen by the browser, it's not something the application can control. – Barmar Apr 12 '16 at 21:05
  • Thanks. I tried localStorage.setItem("Rob", "this_is_it"); I would have thought it would have written the value "this_is_it" out to a file. I did a PowerGrep for "this_is_it" but nothing came back. Am I missing something? – Rob Apr 12 '16 at 23:20
0

I got this to work and write out a file using the following function:

function write_it(win){

var textToWrite = win;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = "win.txt"

var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";

downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
downloadLink.click();

}

Rob
  • 189
  • 2
  • 11