我正在测试plus_one应用程序,在运行它的同时,我只是想澄清一下我关于event.once()和event.on()的概念。
这是plus_one.js
> process.stdin.resume();
process.stdin.on('data',function(data){
var number;
try{
number=parseInt(data.toString(),10);
number+=1;
process.stdout.write(number+"\n");
}
catch(err){
process.stderr.write(err.message+"\n");
}
});
这是test_plus_one.js
var spawn=require('child_process').spawn;
var child=spawn('node',['plus_one.js']);
setInterval(function(){
var number=Math.floor(Math.random()*10000);
child.stdin.write(number+"\n");
child.stdout.on('data',function(data){
console.log('child replied to '+number+' with '+data);
});
},1000);
在使用child.stdin.on()时,我收到了一些maxlistener偏移警告,但使用child.stdin.once()时却不是这样,为什么会发生这种情况?
是因为child.stdin正在监听之前的输入吗?但在这种情况下,应该更频繁地设置maxlistener偏移量,但它只会立即发生一次或两次。
发布于 2013-09-11 21:23:05
使用EventEmitter.on()
时,您可以附加一个完整的侦听器,而当您使用EventEmitter.once()
时,它是一个一次性侦听器,在触发一次之后将分离。只触发一次的监听程序不计入最大监听程序计数。
发布于 2018-07-25 10:05:29
根据最新的官方文档https://nodejs.org/api/events.html#events_eventemitter_defaultmaxlisteners。.once()侦听器确实计入了maxlisteners。
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
https://stackoverflow.com/questions/18740123
复制相似问题