Search code examples
javascriptnode.jstwitter-streaming-apintwitter

ntwitter: stop listening on stream events after X callback


//Totally new to node.js

I'm using ntwitter to listen on twitter statuses. How can I stop listening after X callback were called?

 var twittsCounter = 0;
 twit.stream('statuses/filter', {track:['cool','awesome','fuck yeah!']}, function(stream) {
  stream.on('data', function (tweet) {
    twittsCounter += 1;
    console.log(twittsCounter + ":" + tweet.text);
    if (twittsCounter > 100){
      //stop listening? 
    }

  });

Solution

  • Factor your event handler into a separate function. Then use

    stream.on('data', myDataHandler)
    

    ... and in myDataHandler just use stream.removeListener('data', myDataHandler).

    stream is "just" an EventEmitter, here are the docs: http://nodejs.org/api/events.html