line-by-line icon indicating copy to clipboard operation
line-by-line copied to clipboard

close() method does not trigger end event

Open FrancisTurner opened this issue 7 years ago • 2 comments

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.

FrancisTurner avatar May 02 '17 12:05 FrancisTurner

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.

superhawk610 avatar Jul 05 '17 16:07 superhawk610

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)

yourimiyi avatar Dec 16 '17 03:12 yourimiyi