Can you save/load a file via Javascript?

痞子三分冷 提交于 2019-12-14 01:37:38

问题


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


回答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.




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



回答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?




回答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/



来源:https://stackoverflow.com/questions/17956343/can-you-save-load-a-file-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!