在nodejs中区分b/w event.on()和event.once()

Ana*_*ued 27 child-process node.js eventemitter

我正在测试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");
        }
    });
Run Code Online (Sandbox Code Playgroud)

这是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);
Run Code Online (Sandbox Code Playgroud)

在使用child.stdin.on()时我得到的maxlistener偏移警告很少但是在使用child.stdin.once()时不是这种情况,为什么会发生这种情况?

是因为child.stdin正在听以前的输入吗?但是在这种情况下,maxlistener偏移量应该更频繁地设置,但它只会在一分钟内发生一次或两次.

hex*_*ide 44

使用时EventEmitter.on(),附加一个完整的侦听器,与使用时相比EventEmitter.once(),它是一次性侦听器,在触发一次后将分离.仅触发一次的监听器不计入最大监听器计数.


小智 7

根据最新的官方文档https://nodejs.org/api/events.html#events_eventemitter_defaultmaxlisteners。.once() 侦听器确实计入最大侦听器。

emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
  // do stuff
  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
Run Code Online (Sandbox Code Playgroud)