从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);});
即使没有final,也可以正确读取最后一行(从Node v0.12或更高版本开始)
n。
更新
:此示例已添加到Node的API官方文档中。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)