在 nodejs 中发出 rl.close() 后,readline 不会停止行读取 [英] readline doesn't stop line reading after rl.close() emit in nodejs
问题描述
我有以下文件,我想逐行读取并在找到nameserver 8.8.8.8"后停止读取.
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
我正在使用 nodejs 和 readline 模块来这样做
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();
由于我在读取第一个匹配项后立即使用 rl.close() 发出关闭事件,因此我希望我的代码仅读取第一行,然后停止进一步读取.但是我的输出看起来像这样
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
如何在第一场比赛后让 readline 停止并让我继续做其他事情?
How can I make readline stop after first match and let me proceed with a something else?
推荐答案
对于那些无法让 linereader 停止的人,请执行以下操作(在您的 readline 回调中):
for those of you who can't make the linereader stop, do this (in your readline callback):
lineReader.close()
lineReader.removeAllListeners()
这篇关于在 nodejs 中发出 rl.close() 后,readline 不会停止行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!