2

我希望创建第一个节点 js 应用程序。为此,我需要拉出公共推特推文并将推文作为请求响应输出。我搜索了很多,但我得到了用旧节点版本代码编写的代码(即 createServer、addListener 之类的)。我们如何编写请求 twitter 调用的代码并将 json 作为节点版本 0.6.18 中的响应输出?

以下是我尝试过的旧代码

var http = require("http");
var events = require("events");
var port = 8001;
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 + "/");

并得到错误

$ node tweet.js 
Server running at http://localhost:8001/

timers.js:223
    callback.apply(timer, args);
             ^
TypeError: Cannot call method 'apply' of undefined
    at Timer.ontimeout (timers.js:223:14)
4

1 回答 1

1

你的错误很常见。代替:

setInterval(getTweats(), 1000);

你需要

setInterval(getTweats, 1000);

这是因为您要setInterval调用getTweats函数本身

您的代码getTweats()带有括号。这首先调用 getTweats,并将结果提供给setInterval. 由于这个结果是undefined(你的函数不返回任何东西),节点不能调用它。

于 2012-07-26T12:38:53.510 回答