How can you read a file line by line in JavaScript?

I am writing a web application for the iPad that will download data from a text file. (An approximate data set is about 400 kb). I have everything except reading the file. As I installed my code, you are passing an object that reads the file line by line.

How can I read a file line by line?

If there is no direct way to read a file line by line, can someone show me an example of how to read a file into a string object? (so I can use the split: P method)

+6
source share
4 answers

This might work if I figured out what you want to do:

var txtFile = new XMLHttpRequest(); txtFile.open("GET", "http://website.com/file.txt", true); txtFile.onreadystatechange = function() { if (txtFile.readyState === 4) { // document is ready to parse. if (txtFile.status === 200) { // file is found allText = txtFile.responseText; lines = txtFile.responseText.split("\n"); } } } txtFile.send(null); 
+11
source

Mobile Safari does not have a File API , so I assume you are talking about reading from a web resource. You cannot do this. When you read a resource through ajax, the browser will first read it completely in memory, and then pass the entire string to your ajax callback as a string.

In your callback, you can take a line and break it into lines and wrap it in an object that has an API that your code needs, but you will still have the line in memory right away ..

+2
source

Using jQuery:

 myObject = {}; //myObject[numberline] = "textEachLine"; $.get('path/myFile.txt', function(myContentFile) { var lines = myContentFile.split("\r\n"); for(var i in lines){ //here your code //each line is "lines[i]" //save in object "myObject": myObject[i] = lines[i] //print in console console.log("line " + i + " :" + lines[i]); } }, 'text'); 
+2
source

I do not think this is possible until you use ajax to get the server side code.

0
source

Source: https://habr.com/ru/post/893788/


All Articles