line-by-line
line-by-line copied to clipboard
close() method does not trigger end event
The close() method on its own seems to do very little. It does close the file but does not, of itself, stop subsequent line events or emit the end event as stated in the dcumentation - https://www.npmjs.com/package/line-by-line
close()
Stops emitting 'line' events, closes the file and emits the 'end' event.
Code similar to the following
const LineByLineReader = require('line-by-line');
var lr = new LineByLineReader('file.txt',
{ encoding: 'utf8', skipEmptyLines: true });
var rx='';
lr.on('error', function(err) {
// 'err' contains error object
console.log(err.message);
process.exit();
});
lr.on('line', function(line) {
if (line.includes ('===END MARKER===')) {
console.log("Finito");
lr.close();
lr.pause();
}
console.log("Processing " + line);
rx+='|\\.'+line.replace(/\./g,'\\.');
});
lr.on('end', function () {
console.log("result regex "+ rx);
});
never prints a "result regex" line and if I omit the pause call then lines after the "END MARKER" line are also processed.
On the other hand code like this does emit an end event:
const LineByLineReader = require('line-by-line');
var lr = new LineByLineReader('file.txt',
{ encoding: 'utf8', skipEmptyLines: true });
var rx='';
var done=false;
lr.on('error', function(err) {
// 'err' contains error object
console.log(err.message);
process.exit();
});
lr.on('line', function(line) {
if (line.includes ('===END MARKER===')) {
console.log("Finito");
done=true;
}
if (done ) return; // skip lines after end marker
console.log("Processing " + line);
rx+='|\\.'+line.replace(/\./g,'\\.');
});
lr.on('end', function () {
console.log("result regex "+ rx);
});
This seems to be contrary to the documentation. It is inefficient to continue processing, particularly if the END MARKER line shows up near the front of the file.
It appears as if the documentation may have simply used the wrong function name. lr.close()
does nothing for me, but lr.end()
seems to perform as expected, ending 'line' events, closing the file, and calling the 'end' handler.
when calling .pause()
before .close()
it happens.
.close()
destroys stream then call _nextLine()
and that just returns.
because .pause()
set the variable this._paused
to true.
so call .end()
after .close()
immediately. (if not stream will not destroyed)