如何在 JavaScript 中逐行读取文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6861180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:31:15  来源:igfitidea点击:

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

javascriptipadfile-io

提问by Ryan Amos

I'm writing a web-app for the iPad that will be loading data from a text file. (A sample data set is around ~400 kb). I have everything set up except the file reading. The way I have set up my code, you pass an object which reads a file line by line.

我正在为 iPad 编写一个网络应用程序,它将从文本文件加载数据。(样本数据集约为 400 kb)。除了文件读取之外,我已经设置了所有内容。按照我设置代码的方式,您传递了一个逐行读取文件的对象。

How can I read a file line by line?

如何逐行读取文件?

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

如果没有直接逐行读取文件的方法,有人可以向我展示如何将文件读入字符串对象的示例吗?(这样我就可以使用拆分方法:P)

回答by afaf12

This could work, if I understood 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);

回答by T.J. Crowder

Mobile Safari doesn't have the File API, so I assume you're talking about reading from a web resource. You can't do that. When you read a resource via ajax, the browser will first read it fully into memory and then pass the entire string to your ajax callback as a string.

Mobile Safari 没有File API,所以我假设您在谈论从 Web 资源读取。你不能那样做。当您通过 ajax 读取资源时,浏览器将首先将其完全读入内存,然后将整个字符串作为字符串传递给您的 ajax 回调。

In your callback, you can take the string and break it into lines, and wrap that up in an object that has the API that your code wants, but you're still going to have the string in memory all at once..

在您的回调中,您可以将字符串分成几行,然后将其包装在具有您的代码所需的 API 的对象中,但您仍然会立即将字符串全部保存在内存中。

回答by geralOE

With jQuery:

使用 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');

回答by sushil bharwani

i dont think thats possible until you use ajax to hit some server side code.

我不认为那是可能的,直到您使用 ajax 命中某些服务器端代码。