Search code examples
javascriptfilefopenfread

Javascript examples found on severial sites regarding fopen is not working for me


I am trying to read a text file that is in the same directory as my html file using javascript so that I might include the contents of the text file in my html file.

Here is the code I have to test the fopen and fread functions

<html>

<head>

</head>

<body>
<script>
   fh = fopen('my.txt', 0); // Open the file for reading.
   if(fh!=-1) // Check if the file has been successfully opened.
   {
   length = flength(fh); // Get the length of the file.
   str = fread(fh, length); // Read in the entire file.
   fclose(fh); // Close the file.
   
   // Display the contents of the file.
   write(str);
   } 
</script>
</body>

</html>

I've tried replacing the 'write' with document.write and still nothing.

Here are some websites that had this code as an example:

http://answers.yahoo.com/question/index?qid=20130519190823AA2lQ1W

http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm

Any help at all would be much appreciated.

Thank you!


Solution

  • Javascript has no filesystem access. As it is mentioned in the second link you posted, you will need to install special plugins in order to give JS file system access.

    I don't think it is the right way to accomplish whatever you are trying to do.

    In order to access client's filesystem, the popular way I've seen is using Flash or Java applet or Microsoft Silverlight for that matter.

    For accessing your server filesystem, you will need to run a web server which has proper permissions to access the filesystem. Then, you can make AJAX calls to the web server, which in turn will fetch the file for you.