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 :)
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();
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With