2

I am trying to read a file in the same directory of an HTML and JavaScript file however it seems to be returning null. Below I have added the code I have from each file.

HTML File:

<html>
    <!-- Code to call the Google Maps API and link style.css sheet -->
<body>
    <div class="content">
        <div id="googleMap"></div>
        <div id="right_pane_results">hi</div>
        <div id="bottom_pane_options">
            <button onclick="get_parameters()">Try It</button>
        </div>
    </div>
</body>
<script type="text/javascript" src="./javascript.js">
    </script>
</html>

JavaScript File:

function get_parameters() {
    alert("hi"); // Just to let me know the function is getting called
    var freader = new FileReader();

    var text;
    freader.onload = function(e) {
        text = freader.result; 
    }
    freader.readAsText('./test.txt', "ISO-8859-1");
    text = freader.result; // To my knowledge, this should be taking the current line freader is on and storing it into text

    var div = document.getElementById('bottom_pane_options');
    div.innerHTML = div.innerHTML + text;
}

test.txt

Iron
Aluminum
Steel
//etc. for x number of times (depends on data I have parsed previously)

All I would like is for JavaScript to read test.txt and parse it into an array (text). The issue is, when I click the button 'Try It', the alert pops up (telling me the function is being called) and text contains null. I am running all files off my computer and all are in the exact same directory.

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3015565
  • 393
  • 3
  • 6
  • 16
  • 1
    [FileReader.readAsText()](https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsText): _When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the contents of the file as a text string._ – Andreas Jan 15 '14 at 22:06
  • I'm afraid, only [Blob and File](https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsText) objects can be passed into `readAstext`, not strings. See [an example](http://jsfiddle.net/0GiS0/nDVYd/) of using this function. – lexasss Jan 15 '14 at 22:34
  • @Andreas If that is true, why does `text = freader.result;` not give me the contents of the file? Why is `text == null` when I print to the `div` on the last line of the JavaScript file code? – user3015565 Jan 15 '14 at 23:25
  • Because `.readAsText()` is **async**. The script doesn't stop at the call of `.readAsText()` and waits for the result of the call but goes directly to the next instruction. – Andreas Jan 16 '14 at 06:15
  • Possible duplicate of [HTML5 FileReader how to return result?](http://stackoverflow.com/questions/11829537/html5-filereader-how-to-return-result) – Ruslan López Feb 27 '16 at 02:28

0 Answers0