-4
  1. I have a text file which is having a set of qns.
  2. The file is present in the same path as my javascript file.
  3. I need to read the file and store it in a js array.

Ex :

xxx.txt

  1. First question
  2. Second question

Result : 1. Js array should store every line seperately.

  • possible duplicate of [reading server file with javascript](http://stackoverflow.com/questions/13329853/reading-server-file-with-javascript) – Alex Jan 07 '15 at 12:38
  • 1
    JavaScript has no native way to read files. How you do it depends on your host environment. What is your host environment? Is it a web page? Node.js? Windows Scripting Host? ASP Classic? Something else? – Quentin Jan 07 '15 at 12:39
  • 2
    Please limit yourself to one question per question. – Quentin Jan 07 '15 at 12:39
  • Javascript runs on the client and your text file is hosted on the server; Because of that, you need to issue a request to the file, which can be done through AJAX. A first thing would be to request the file, then when you get the response, process it to turn that text response into a javascript array. – Laurent S. Jan 07 '15 at 12:39
  • Are you talking about javascript in the browser or are you using node.js to run it on the server? You cannot real files on the server from javascript running in the client. – Niels Abildgaard Jan 07 '15 at 12:41
  • Possible duplicates http://stackoverflow.com/questions/23331546/how-to-use-javascript-to-read-local-text-file-and-read-line-by-line – Dotnetpickles Jan 07 '15 at 12:56

1 Answers1

1
<!DOCTYPE html>
<html>

   <head> 

       <script type="text/javascript" src="jquery.min.js"></script>
       <script type="text/javascript">

            var file_path = "other.txt";
            var output_array = new Array(); // __output array
            var arr = 0;
            var line = "";

            $(document).ready(function(){
                  $.get(file_path, function(data) {
                        for(i = 0; i < data.length; i++){
                            if(data[i] == '\n' || i == ( data.length - 1 )){
                                output_array[arr] = line; arr++; line = "";
                                continue;
                            }
                            line = line + data[i];   
                        } // __creating lines

                        // __testing it
                        for(i = 0; i < output_array.length; i++) alert(output_array[i]);  // __line for testing purpuse

                  }, 'text');

            });  // __document.ready        

       </script>

   </head>

   <body>
   </body>

</html>

//__ Working in Mine :), Thanks

Tiger
  • 404
  • 1
  • 4
  • 13