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

时间:2011-09-11 15:38:56

标签: node.js

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

现在,我的问题是没有读取文件。我知道该怎么做。我不确定的是如何让它读入数组中的一行,以便程序可以做我应该做的任何事情,并在完成使用那一行数字时读到下一行

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

关于如何使程序一次只读入一行数据的任何提示将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用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);
}