Skip to main content
Participant
April 20, 2010
Question

Difficulty reading file into variable.

  • April 20, 2010
  • 1 reply
  • 420 views

I'm having trouble reading a file into a string and can't figure out why.

var myFile = new File( '/path/to/my/file.xml' );

var myFileString = myFile.read();

alert( myFileString.length ); // displays 0

Does anybody know what could be going on here? It seems like such a simple operation.

Thanks.

This topic has been closed for replies.

1 reply

tjlahr10Author
Participant
April 20, 2010

I think I figured it out.

The file has be opened first with myFile.open('r');

Inspiring
April 20, 2010

Yes you are right.

Here is Javascript reference for file.Open()

fileObj.open (mode[,type][,creator])
mode A string indicating the read/write mode. One of:
➤ r: (read) Opens for reading. If the file does not exist or cannot be found, the call fails.
➤ w: (write) Opens a file for writing. If the file exists, its contents are destroyed. If
the file does not exist, creates a new, empty file.
➤ e: (edit) Opens an existing file for reading and writing.
➤ a: (append) Opens the file in Append mode, and moves the current position to the end of the file.
type Optional. In Mac OS, the type of a newly created file, a 4-character string. Ignored in Windows and UNIX.
creator Optional. In Mac OS, the creator of a newly created file, a 4-character string. Ignored in Windows and UNIX.
and you must close a file after opening it.

var myFile = new File( '/path/to/my/file.xml' );

myFile.open("r");//for open real only

var myFileString = myFile.read();

myFile.close();

alert( myFileString.length);

Shonky