readline doesn't stop line reading after rl.close() emit in nodejs : <p>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".</p>

<pre><code>nameserver 8.8.8.8
nameserver 45.65.85.3
nameserver 40.98.3.3
</code></pre>

<p>I am using nodejs and the readline module to do so</p>

<pre><code>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) =&gt; {
    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();
</code></pre>

<p>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</p>

<pre><code>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
</code></pre>

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