- I have a text file which is having a set of qns.
- The file is present in the same path as my javascript file.
- I need to read the file and store it in a js array.
Ex :
xxx.txt
- First question
- Second question
Result : 1. Js array should store every line seperately.
-
possible duplicate of reading server file with javascriptAlex– Alex2015年01月07日 12:38:10 +00:00Commented Jan 7, 2015 at 12:38
-
1JavaScript 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– Quentin2015年01月07日 12:39:03 +00:00Commented Jan 7, 2015 at 12:39
-
2Please limit yourself to one question per question.Quentin– Quentin2015年01月07日 12:39:22 +00:00Commented 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.Laurent S.– Laurent S.2015年01月07日 12:39:56 +00:00Commented 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.Niels Abildgaard– Niels Abildgaard2015年01月07日 12:41:16 +00:00Commented Jan 7, 2015 at 12:41
1 Answer 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
answered Jan 7, 2015 at 13:25
Tiger
4341 gold badge4 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js