Skip to content

readline: line emitted after close while processing text file #22615

Closed
@lych77

Description

@lych77
  • Version: v10.9.0
  • Platform: Windows 7 64-bit

Test code:

'use strict';

const fs = require('fs');
const readline = require('readline');

let sampleText = '';
for (let i = 0; i < 10; i++) {
	sampleText += `This is line ${i}\n`;
}
fs.writeFileSync('sample.txt', sampleText);

const file = fs.createReadStream('sample.txt', {encoding: 'utf-8'});
const reader = readline.createInterface(file);

reader.on('line', ln => {
	console.log(ln);
	if (ln.endsWith('4')) {
		reader.close();
	}
});

reader.on('close', () => {
	console.log('closed');
});

Output:

This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
closed
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9

Should this be supposed to happen? What should I do if I want to cancel the reading process under some condition? Is it the only way to maintain some flag myself and check it in the 'line' handler and just ignore the overheads?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions