Node -js twitter json

I am trying to write a simple application with node.js to pull json from twitter.

json loads fine for the first time, however my tweets event doesn't fire correctly.

Does anyone see where I'm wrong? any advice is greatly 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

+3
source share
1 answer

You have two problems:

  • httpClient.request- this is just a request once .
  • You do not pass a function getTweatsto an interval, but its return value :
    setInterval(getTweats() */ <-- parenthesis execute the function */, 1000);

To fix this, create a new query for each call getTweats:

function getTweats() {
     // There no need for request being global, just make it local to getTweats
     var request = twitterClient.request("GET", "/1/statuses/public_timeline.json", {"host": "api.twitter.com"});

And pass the function correctly setTimeout:

setInterval(getTweats, 1000);

PS: ! 15 , , , 5 :)

+4

Source: https://habr.com/ru/post/1784249/


All Articles