Node.js高效按行输出文件内容
const fs = require('fs'); const EventEmitter = require('events'); const util = require('util'); const path = require('path'); function readFileByLine(file) { EventEmitter.call(this); file = path.normalize(file); this.filePath = file; this.lines = []; this.initStream(); this.end = false; } util.inherits(readFileByLine, EventEmitter); readFileByLine.prototype.initStream = function() { let readStream = fs.createReadStream(this.filePath, { encoding: 'utf8' }); readStream.on('data', (data) => { this.readStream.pause(); this.lines = this.lines.concat(data.split(/(?:\n|\r\n|\r)/g)); this.nextLine(); }); readStream.on('end', () => { this.end = true; this.nextLine(); }); this.readStream = readStream; }; readFileByLine.prototype.nextLine = function() { var line; if (this.end) { this.emit('end'); return ; } if (!this.lines.length) { return this.readStream.resume(); } line = this.lines.shift(); line.length && this.emit('line', line); this.nextLine(); }
接口调用API举例
var lr = new readFileByLine('data.txt'); lr.on('line', (line) => { console.log('receive line' + line); }); lr.on('end', () => { console.log('end line reader'); })
参考:https://github.com/RustyMarvin/line-by-line