0

Is there a way to create a text file (and write some JSON data to it ) using client side code only (no server-side code / web services )?

Mayur Arora
  • 447
  • 5
  • 11

3 Answers3

1

You can use local storage to store data client-side, but there is no way to do this server-side.

Cezary Wojcik
  • 21,745
  • 6
  • 36
  • 36
0

My best guess would be that you need to use javascript localstorage to store json.

example :

var myObject = {};
localstorage['myKey'] = myObject;
var secObject = localstorage['mykey'];

//you couls also use :
localstorage.setItem('myKey', myObject);
secObject = localstorge.getItem('myKey');

I usually "stringify" my JSON before saving it in case i need to modify "myObject" after saving it (because when you copy an object you actually copy a reference to it)

localstorage['myKey'] = JSON.stringify(myObject);
secObject = JSON.parse(localstorage['myKey']);
Xeltor
  • 4,626
  • 3
  • 24
  • 26
  • localStorage is like a temp file , that would get deleted when browser cache is cleared. Wat I want is a .txt file in a directory I specify (not somewhere browser stores the cache) – Mayur Arora May 07 '14 at 07:54
0

How are you all missing his point? You are able to generate text files and .csv files on client side and deliver it as a download.

var element = document.createElement('a');
 element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

From this link: https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

F.H.
  • 1,456
  • 1
  • 20
  • 34