About This Product
Search This Database:
| Over 5000 Free Fonts | Tutorials | Javascript Forum | Other Javascript Resources | Cheat Sheet
Tutorial archive
General Questions
Javascript 1.2
Object Model
Reference Manual
Mouse Events
File Access
Control Status Bar
Dates and Time
Client Information

Reading a File

Question: How do I read a file into a JavaScript variable?

Answer: Reading a file from JavaScript is (almost) as easy as reading a file from a Java applet. Your script cannot read files itself; you would have to code a Java applet that reads files for your script.

In more detail, one of the possible reading mechanisms can work like this:

  1. Your script calls a public method of the applet.
  2. The public method initiates the reading process in another thread of the applet, and then returns.
  3. The reading process in another thread of the applet continues. At the same time, the script keeps asking the applet whether the reading is complete.
  4. The applet finishes reading and puts the file content in a public string variable of the applet.
  5. The script sees that the applet completed reading.
  6. The script copies the file content from the applet's public variable into a Javascript variable.
Note that unsigned Java/JavaScript code can read files only if the file(s) to read and the code itself have the same origin. For example, if your unsigned code is published on a Web server, it is allowed to read files from the same server only. If your code resides on the local hard disk, it is allowed to read files only from the same disk (at best).

If you would like to read files that have a different origin, you'll need to sign your code. (For more information, see Writing Files; very similar security considerations apply to reading files whose origin is other than that of your code.)

Here's a simple example that implements the file reading mechanism described above. The rectangle below is a Java applet called ReadURL.class. This applet reads the content of the chosen file into a public variable fileContent. When finished, the applet sets its public variable finished to 1.

The script in this example reads selected files that contain some topics from this JavaScript FAQ.

The JavaScript code that starts the reading process looks as follows:
var fileContent='';
var theLocation='';

function readFileViaApplet(n) {
 document.f1.t1.value='Reading in progress...';

function showFileContent() {
 if (document.ReadURL.finished==0) {