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); }