Node.js如何从文件读取一行数字到数组中

我有一个家庭作业,我有数字文件读入数组,然后对它们做些什么。

现在,我的问题是没有阅读文件。我知道如何做到这一点。 我不确定的是如何让它读入数组中的一行,以便程序可以做我应该做的任何事情,并在完成与该行数字一起工作时读入下一行。

txt文件非常大,每行有90个数字,每行以行返回结束。

任何有关如何让程序一次只读入一行的提示将不胜感激。 谢谢。


我认为最简单的方法是使用fs.Readstream如果文件很大。

var fs = require('fs');

var
  remaining = "";
  lineFeed = "n",
  lineNr = 0;

fs.createReadStream('data.txt', { encoding: 'utf-8' })
  .on('data', function (chunk) {
    // store the actual chunk into the remaining
    remaining = remaining.concat(chunk);

    // look that we have a linefeed
    var lastLineFeed = remaining.lastIndexOf(lineFeed);

    // if we don't have any we can continue the reading
    if (lastLineFeed === -1) return;

    var
      current = remaining.substring(0, lastLineFeed),
      lines = current.split(lineFeed);

    // store from the last linefeed or empty it out
    remaining = (lastLineFeed > remaining.length)
      ? remaining.substring(lastLineFeed + 1, remaining.length)
      : "";

    for (var i = 0, length = lines.length; i < length; i++) {
      // process the actual line
      _processLine(lines[i], lineNr++);
    }
  })
  .on('end', function (close) {
    // TODO I'm not sure this is needed, it depends on your data
    // process the reamining data if needed
    if (remaining.length > 0) _processLine(remaining, lineNr);
  });

function _processLine(line, lineNumber) {
  // UPDATE2 with parseFloat
  var numbers = line.split(" ").map(function (item) { return parseFloat(item); });
  console.log(numbers, lineNumber);
}
链接地址: http://www.djcxy.com/p/52293.html

上一篇: Node.js how to read one line of numbers from a file into an array

下一篇: Iterate through lines in a file with Node.js and CoffeeScript