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

I have a homework assignment where I have files of numbers to read into an array and then do something with them.

Now, my problem isn't reading the files in. I know how to do that. What i'm unsure on is how to get it to read one line into the array, so that the program can do whatever it is I'm supposed to do, and read in the next line when it's done working with that line of numbers.

The txt files are pretty big, with something like 90 numbers per line and each line ended with a line return.

Any tips on how to make the program read just one line into the array at a time would be greatly appreciated. Thank you.


我认为最简单的方法是使用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/52294.html

上一篇: 为django测试加载装置

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