readline doesn't stop line reading after rl.close() emit in nodejs

gvoigt picture gvoigt · May 24, 2017 · Viewed 9.7k times · Source

I have the following file I want to read line by line and stop reading it once I have found "nameserver 8.8.8.8".

nameserver 8.8.8.8
nameserver 45.65.85.3
nameserver 40.98.3.3

I am using nodejs and the readline module to do so

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

function check_resolv_nameserver(){
  // flag indicates whether namerserver_line was found or not
  var nameserver_flag = false;

  const rl = readline.createInterface({
    input: fs.createReadStream('file_to_read.conf')
  });

  rl.on('line', (line) => {
    console.log(`Line from file: ${line}`);
    if (line === 'nameserver 8.8.8.8'){
      console.log('Found the right file. Reading lines should stop here.');
      nameserver_flag = true;
      rl.close();
    }
  });

  rl.on('close', function(){
    if (nameserver_flag === true){
      console.log('Found nameserver 8.8.8.8');
    }
    else {
      console.log('Could not find nameserver 8.8.8.8');
    }
  });
}

check_resolv_nameserver();

Since I emit a close event with rl.close() as soon as I read the first match, I would expect my Code to read only the first line and then stop reading further. But instead my output looks like this

Line from file: nameserver 8.8.8.8
Found the right file. Reading lines should stop here.
Found nameserver 8.8.8.8
Line from file: nameserver 45.65.85.3
Line from file: nameserver 40.98.3.3

How can I make readline stop after first match and let me proceed with a something else?

Answer

Oz Shabat picture Oz Shabat · Sep 5, 2019

for those of you who can't make the linereader stop, do this (in your readline callback):

lineReader.close()
lineReader.removeAllListeners()