0

I have a number of variables that record a "save" state in javascript that I would like to save and load on the users computer locally.

Basically its the entire content of a single .js file which I called "variables.js"

Is there an easy way to save all the data in the file and to load it just as easily?

Meredori
  • 131
  • 8
  • 1
    HTML5 offers [local storage](http://www.html5rocks.com/en/features/storage) – SubjectCurio Jul 28 '14 at 14:52
  • You can't save to a users file system without their knowledge - you can use `localStorage` however. – tymeJV Jul 28 '14 at 14:52
  • You could try saving the individual variables in cookies or with the Web Storage API (session storage or local storage). Actually, saving the files though is not possibly as far as I know. Not without prompting the user at least. – War10ck Jul 28 '14 at 14:52

2 Answers2

3

Try window.localStorage:

var localStorage = window.localStorage;
var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);

The data can be any type supported by JavaScript, including strings, Booleans, integers, or floats. However, the data is actually stored as a string. So if you want to store object literals (as you might want to do within angular), you can use angular.toJson() and angular.fromJson():

var person = { name: 'jake' };
localStorage.setItem("person", angular.toJson(person));
var t = angular.fromJson(localStorage.getItem("person"))
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • See http://stackoverflow.com/questions/4692245/html5-local-storage-fallback-solutions for a solution that supports `localStorage` along with suitable fallback options when a browser doesn't support `localStorage` – Baldy Jul 28 '14 at 14:56
2

So if i understand it correctly you have a file like this:

//data.js
var firstName = "Hans";
var lastName = "Muster";
var age = 18;

And you want to be able to save & load the contents of those variables to/from the disk?

If that's the case, then no. But you can store your data in a single object and then save this in the localStorage of the user in the JSON format.

Example:

//data.js
var data = {
    firstName:"Hans",
    lastName:"Muster",
    age:18
}

To save it:

localStorage["data"] = JSON.stringify(data);

To load it:

data = JSON.parse(localStorage["data"]);
Van Coding
  • 24,244
  • 24
  • 88
  • 132
  • Just like to say this worked wonders. Copied all my variables into data on save, then copied them back out on load. :) – Meredori Jul 28 '14 at 16:21