How to read and write into file using JavaScript?

2018-12-31 04:30发布

Can anybody give some sample code to read and write a file using JavaScript?

16条回答
浪荡孟婆
2楼-- · 2018-12-31 05:24

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.

查看更多
梦该遗忘
3楼-- · 2018-12-31 05:25

For Firefox:

var file = Components.classes["@mozilla.org/file/local;1"].
       createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home");

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.

查看更多
大哥的爱人
4楼-- · 2018-12-31 05:25

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:

  1. 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.

  2. 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.

  3. 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.

查看更多
只靠听说
5楼-- · 2018-12-31 05:26

From a ReactJS test, the following code successfully writes a file:

import writeJsonFile from 'write-json-file';

const ans = 42;
writeJsonFile('answer.txt', ans);

const json = {"answer": ans};
writeJsonFile('answer_json.txt', json);

The file is written to the directory containing the tests, so writing to an actual JSON file '*.json' creates a loop!

查看更多
登录 后发表回答