Canvas
Canvas

Reputation: 5897

Can you save/load a file via Javascript?

I want to create a very simple Javascript game using HTML5 (Canvas). But is it possible to save a simple .txt file and load a simple .txt file. I just need to store like the some simple integers. But I just want to know if javascript is allowed to save and load an external file?

Canvas

Upvotes: 4

Views: 35849

Answers (4)

Alex
Alex

Reputation: 1641

Since html5 you can use the LocalStorage API. Nowadays almost all browsers support it:

// Check if it is supported in your browser
function supports_html5_storage()
{
      try
      {
        return 'localStorage' in window && window['localStorage'] !== null;
      }
      catch (e)
      {
        return false;
      }
}

//make use of it:
if( supports_html5_storage() == true )
{
   localStorage.setItem("myItem", "myData");
   var myDataString = localStorage.getItem("myItem");
   alert(myDataString);
}

Upvotes: 4

Damiaan Dufaux
Damiaan Dufaux

Reputation: 4795

You can't access the local file system directly with javascript, but it is possible when you let the user interact (for example by letting the user select a file to upload). See http://www.html5rocks.com/en/tutorials/file/dndfiles/

Another possibility is local storage. See http://davidwalsh.name/html5-storage, http://www.w3.org/TR/webstorage/

Upvotes: 1

MatteoSp
MatteoSp

Reputation: 3048

On Chrome, you can rely on the FileSystem API (for an intro take a look here). Probably other browsers will soon add support to it.

But, if your need is just "to store like the some simple integers" I would consider local storage.

Upvotes: 3

jds
jds

Reputation: 8279

In short, no. According David Flanagan's "JavaScript: The Definitive Guide":

Input and output (as well as more sophisticated features, such as networking, storage, and graphics) are the responsibility of the 'host environment' within which JavaScript is embedded.

The bigger question is why. Think about how dangerous it would be if JavaScript could write files to your hard drive. What if any website you visited could access your local file system?

Upvotes: 2

Related Questions