Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Difference b/w event.on() and event.once() in nodejs

Difference b/w event.on() and event.once() in nodejs

Problem

I'm testing the plus_one app, and while running it, I just wanted to clarify my concepts on event.once() and event.on()

This is 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");
        }
    });

and this is 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);

I get few Maxlistener Offset warning while using child.stdin.on() but this is not the case when using child.stdin.once(), why is this happening ?

Is it because child.stdin is listening to previous inputs ? but in that case maxlistener offset should be set more frequently, but its only happening for once or twice in a minute.

Problem courtesy of: Anathema.Imbued

Solution

Using EventEmitter.on(), you attach a full listener, versus when you use EventEmitter.once(), it is a one time listener that will detach after firing once. Listeners that only fire once don't count towards the max listener count.

Solution courtesy of: hexacyanide

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Difference b/w event.on() and event.once() in nodejs

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×