i’m trying to write a simple app with node.js to pull some json from twitter..
json loads ok the first time, however, my ‘tweets’ event isnt getting triggered correctly..
anyone see where I’m going wrong? any advice hugely appreciated !
var twitterClient = http.createClient(80, 'api.twitter.com');
var tweetEmitter = new events.EventEmitter();
var request = twitterClient.request("GET", "/1/statuses/public_timeline.json", {"host": "api.twitter.com"});
function getTweats() {
request.addListener("response", function (response) {
var body = "";
response.addListener("data", function (data) {
body += data;
});
response.addListener("end", function (end) {
var tweets = JSON.parse(body);
if (tweets.length > 0) {
tweetEmitter.emit("tweets", tweets);
console.log(tweets, 'tweets loaded');
}
});
});
request.end();
}
setInterval(getTweats(), 1000);
http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
console.log(uri);
if (uri === '/stream') {
var cb = function (tweets) {
console.log('tweet'); // never happens!
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(JSON.stringify(tweets));
response.end();
clearTimeout(timeout);
};
tweetEmitter.addListener("tweets", cb);
// timeout to kill requests that take longer than 10 secs
var timeout = setTimeout(function () {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(JSON.stringify([]));
response.end();
tweetEmitter.removeListener("tweets", cb);
}, 10000);
} else {
loadStaticFile(uri, response);
}
}).listen(port);
console.log("Server running at http://localhost:" + port + "/");
see full file @ https://gist.github.com/770810
You have two problems here:
httpClient.requestis just that, a one time request.getTweatsto the interval, but its return value:setInterval(getTweats() */ <-- parenthesis execute the function */, 1000);In order to fix it, create a new request for each call of
getTweats:And pass the function correctly to
setTimeout:PS: Thx for the gist! Took me like 15 seconds to figure it out from there, always great when people post more than just 5 lines of out of context code 🙂