2017-04-02 62 views
0

我对NodeJS相当陌生,想知道如何让我的节点服务器不断更新网页。如何使用NodeJS更新网页?

所以我正在做的是我从Twitter获取推文,现在我只想在基本网页上显示它们。在第一次运行期间,它看起来像这样:

名称:ap。 Text:RT @APCentralRegion:俄罗斯诗人Yevgeny Yevtushenko 专注于战争暴行的人,死于俄克拉荷马州 姓名:ap。文字: 一个星期后,数百人参加了在俄罗斯的反政府抗议活动,警方在未经授权的集会上逮捕了几十人。 ...

然而,约一分钟,我得到了以下错误消息的时间间隔后:

response.write("*********End of One Interval*********") 
       ^
TypeError: Cannot read property 'write' of undefined 

我的代码如下,请记住,当我里面有鸣叫功能我createServer它仍然表明,它未能妥善更新页面的相同的行为,但是,在终端窗口总是正确更新使用的console.log

// Dependencies ========================= 
var 
    twit = require('twit'), 
    config = require('./config'); 

var http = require("http"); 
var url = require("url"); 

var Twitter = new twit(config); 


// FAVORITE BOT==================== 
// Heavily modified from original tutorial. 

var favoriteTweet = function(response, a, b){ 

     var params = { 
     screen_name: a, 
     count: b, 
//  q: '#aprilfools, #aprilfoolsday', // REQUIRED 
//  result_type: 'recent', //recent tweets only. 
     //lang: 'en' 
    } 

     //console.log("Params: " + params.q); 
     // find the tweet 
     Twitter.get('statuses/user_timeline', params, function(err,data){ 

     // find tweets 
      //console.log(data); 
     var tweet = data; //.statuses for actual tweets. 
     //console.log(tweet); 


     for(var result in tweet) { 
      response.write("Name: " + a + ". Text: " + tweet[result].text + "\n"); 
      console.log("Resulting text: " + tweet[result].text); 
      console.log("Created At: " + tweet[result].created_at); 
     } 

     //console.log(tweet); 
      response.write("*********End of One Interval*********") 
     console.log("*********End of One Interval*********")  
     }); 
    } 

http.createServer(function(request, response) { 

    response.writeHead(200, {"Content-Type":"text/plain"}); 
     var params = url.parse(request.url, true).query; 

     var a = params.name; 
     var b = parseInt(params.count); 


     // grab & 'favorite' as soon as program is running... 
     favoriteTweet(response, a, b); 

     // 'favorite' a tweet in every 1 minute 
     setInterval(favoriteTweet, 60000); 


}).listen(9090); 

回答

1

你要通过argum进入回调。做到以下几点:

setInterval(function(){ 
     favoriteTweet(response,a,b) 
}, 60000); 
+0

这样一个简单的解决方案,非常感谢。我一直在JavaScript中忘记回调。 – SomeStudent