Can anybody give some sample code to read and write a file using JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
You'll have to turn to Flash, Java or Silverlight. In the case of Silverlight, you'll be looking at Isolated Storage. That will get you write to files in your own playground on the users disk. It won't let you write outside of your playground though.
For Firefox:
See https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O
For others, check out the TiddlyWiki app to see how it does it.
In the context of browser, Javascript can READ user-specified file. See Eric Bidelman's blog for detail about reading file using File API. However, it is not possible for browser-based Javascript to WRITE the file system of local computer without disabling some security settings because it is regarded as a security threat for any website to change your local file system arbitrarily.
Saying that, there are some ways to work around it depending what you are trying to do:
If it is your own site, you can embed a Java Applet in the web page. However, the visitor has to install Java on local machine and will be alerted about the security risk. The visitor has to allow the applet to be loaded. An Java Applet is like an executable software that has complete access to the local computer.
Chrome supports a file system which is a sandboxed portion of the local file system. See this page for details. This provides possibly for you to temporarily save things locally. However, this is not supported by other browsers.
If you are not limited to browser, Node.js has a complete file system interface. See here for its file system documentation. Note that Node.js can run not only on servers, but also any client computer including windows. The javascript test runner Karma is based on Node.js. If you just like to program in javascript on the local computer, this is an option.
From a ReactJS test, the following code successfully writes a file:
The file is written to the directory containing the tests, so writing to an actual JSON file '*.json' creates a loop!