Reading a File

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

Answer: Depending on the environment in which your script runs and where the file resides, your options include the following:

For a discussion of the former two options, please follow the above hyperlinks.

Below we'll discuss the latter option - a Java "helper" applet that reads files for your script. One of the possible reading mechanisms implementing this technique 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 applet 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 available via URLs on 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...';
 document.ReadURL.readFile(theLocation);
 setTimeout("showFileContent()",100);
}

function showFileContent() {
 if (document.ReadURL.finished==0) {
  setTimeout("showFileContent()",100);
  return;
 }
 fileContent=document.ReadURL.fileContent;
 document.form1.textarea1.value=fileContent;
}

Copyright © 1999-2011, JavaScripter.net.