-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.

6
  • possible duplicate of reading server file with javascript Commented Jan 7, 2015 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? Commented Jan 7, 2015 at 12:39
  • 2
    Please limit yourself to one question per question. Commented Jan 7, 2015 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. Commented Jan 7, 2015 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. Commented Jan 7, 2015 at 12:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.