如何在 JavaScript 中逐行读取文件? [英] How can you read a file line by line in JavaScript?

查看:73
本文介绍了如何在 JavaScript 中逐行读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

如何逐行读取文件?

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

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)

推荐答案

如果我理解你想做什么,这可以工作:

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("
");
    }
  }
}
txtFile.send(null);

这篇关于如何在 JavaScript 中逐行读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆