Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an infinite loop impossible in nodejs?

For some reason I'm trying to conceive a simple script that can retrieve tweets from a given twitter account and then make something with it (that's not really the relevant part). Following a friend's advice I tried to do it in nodejs. He helped me a little (gave me some code actually) and I managed to get something working. So if I want to retrieve all tweets from one user it works perfectly fine. But actually what I would like is to loop and check the new tweets. But when I wrap my code in a simple while(1) (and modify it as needed) it doesn't do anything. So here's my code :

var tweetFetcher = require('./tweetFetcher');
var codeExtractor = require('./codeExtractor');
var open = require('open');
var fs = require('fs');
var filters = [filter1, filter2];
var hasfirstpart = 0;
var code = "";
var tweets;
var i = 0;
while(1){
    tweets = tweetFetcher.getFrom('twitteraccount', function(tweets) {
        console.log(tweets[0]);
        if(tweets[0].indexOf(filters[hasfirstpart]) > -1){
            code += codeExtractor.extract(tweets[0]).substring(3);
            hasfirstpart = (hasfirstpart+1)%2;  
            console.log(code);
        }
        if(hasfirstpart == 0 && code != ""){
            ...
        }
    });
}



var parser = require('cheerio');
var request = require('request');


exports.getFrom = function(username, cb) {
    var url = "http://twitter.com/"+username;

    request(url, function(err, resp, body) {
        var $ = parser.load(body);
        var tweets = [];
        $('.ProfileTweet-text').each(function() {
            tweets.push($(this).text());
        });

        if(typeof cb == 'function') {
            cb(tweets);
        }
    });
}

Do you have any idea why it cannot be wrapped in a loop ? Thanks in advance for your response :)

like image 414
Nico Avatar asked Oct 01 '22 13:10

Nico


1 Answers

You can't use while (1) in node.js with IO operations, because it will block event loop and prevent all callbacks from being called. If you want to do something forever you need to use recursion instead:

function doThing () {
    tweetFetcher.getFrom('twitteraccount', function(tweets) {
        ...

        doThing();
    });
}
like image 72
vkurchatkin Avatar answered Oct 13 '22 11:10

vkurchatkin