我正在尝试一次一行读取一个大文件。我在 Quora 上发现了一个涉及该主题的问题,但我缺少一些联系来使整个事情融为一体。
var Lazy=require("lazy");
new Lazy(process.stdin)
.lines
.forEach(
function(line) {
console.log(line.toString());
}
);
process.stdin.resume();
我想弄清楚的是如何从文件中一次读取一行,而不是像本示例中那样从 STDIN 中读取。
我尝试过:
fs.open('./VeryBigFile.csv', 'r', '0666', Process);
function Process(err, fd) {
if (err) throw err;
// DO lazy read
}
但它不起作用。我知道在紧要关头我可以重新使用 PHP 之类的东西,但我想弄清楚这一点。
我认为另一个答案不起作用,因为该文件比我运行它的服务器的内存大得多。
正确答案
自 Node.js v0.12 和 Node.js v4.0.0 起,有一个稳定的 readline核心模块。这是从文件中读取行的最简单方法,无需任何外部模块:
const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('rn') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
或者:
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});
lineReader.on('line', function (line) {
console.log('Line from file:', line);
});
lineReader.on('close', function () {
console.log('all done, son');
});
即使没有最终的 n
,最后一行也能正确读取(从 Node v0.12 或更高版本开始)。
更新:此示例已添加到 Node 的 API 官方文档.