Can you save/load a file via Javascript?

32,935

Solution 1

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.

Solution 2

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);
}

Solution 3

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?

Solution 4

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/

Share:
32,935
Canvas
Author by

Canvas

Video Games.... VIDEO GAMES https://www.youtube.com/watch?v=lmAQhsBzAQ0 simple as

Updated on July 05, 2022

Comments

  • Canvas
    Canvas almost 2 years

    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