How to properly remove event listeners in node js eventemitter

You should name the function you attach as event handler. Then on removing it, you just pass the function by name:

app.get('/api/:boardname/remoterefresh', function(req, res){
    var boardname = req.param('boardname')
    function refreshHandler(data){
        setTimeout(function(){
            res.write('data: '+data+'\n\n');
        }, 1000)
    }
    rr.on("refresh-"+boardname, refreshHandler);

    req.socket.setTimeout(Infinity);

    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    });

    res.write('\n');

    req.on('close', function(){
        console.log('closed')
        rr.removeListener("refresh-"+boardname, refreshHandler);
    });
});

Basically removeListener will look up the given function by reference, if it found that function it will remove it from the event hander.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)