在控制台使用& .js的Twitter Feed



我正在尝试创建一个简单的应用程序,使用节点中的Twit模块流推文并将其打印到web控制台。到目前为止,我已经逐字逐句地遵循了Ampersand.js文档。

我的目录结构是:

TwitterLiveFeed/app.bundle.js
TwitterLiveFeed/app.js
TwitterLiveFeed/index.html
TwitterLiveFeed/streamtweets.js
TwitterLiveFeed/package.json
TwitterLiveFeed/node_modules/browserify
TwitterLiveFeed/node_modules/twit

代码如下:

streamtweets.js(模块)

// twitterlivefeed/streamtweets.js
//require the twit npm module
var Twit = require('twit');

function streamTweets() {
    var T = new Twit({
        consumer_key:         '---'
      , consumer_secret:      '---        
      , access_token:         '---'
      , access_token_secret:  '---'
   })
    var stream = T.stream('statuses/sample')
    stream.on('tweet', function (tweet) {
      console.log(tweet)
    })
}
//export streamTweets as the module function
module.exports=streamTweets;

app.js

// ./twitterlivefeed/app.js
console.log("Welcome!")
// require the local module
var streamTweets=require('./streamtweets.js');
// calling function
streamTweets();

然后我运行"./node_modules/.bin/browserify app.js -o app.bundle.js"将应用程序编译成一个文件

index . html

<!-- index.html -->
  <script src='app.bundle.js'></script>

当我在浏览器上运行index.html时,它只是打印"Welcome"。我可以看到Safari错误控制台上的"所有资源的总大小"选项卡的大小不断增加,所以我确信代码正在做一些事情。只是无法得到任何输出。

帮助吗?

EDIT:

所以我编辑我的模块代码到这个,它工作。

var Twit = require('twit');
function streamTweets() {    
var T = new Twit({
    consumer_key:         ''
  , consumer_secret:      ''
  , access_token:         ''
  , access_token_secret:  ''
})
var options = { screen_name: 'username',
                count: 3 };
T.get('statuses/user_timeline', options , function(err, data) {
  for (var i = 0; i < data.length ; i++) {
    console.log(data[i].text);
  }
})

为什么上面的代码可以工作而流不能工作?

查看Twitter文档:

  • https://dev.twitter.com/streaming/overview/connecting

建立到流api的连接意味着发出一个非常长时间的HTTP请求,并增量地解析响应。从概念上讲,你可以把它想象成通过HTTP下载一个无限长的文件。

我认为这通常使浏览器不能作为流的端点"主机"。一个更好的解决方案是在Node.js后端打开一个连接,并通过WebSockets或socket.io

将流发送到客户端。

有很多关于这个的教程:

  • https://scotch.io/tutorials/build-a-real-time-twitter-stream-with-node-and-react-js
  • http://dillonbuchanan.com/programming/node-js-twitter-streaming-api-socket-io-twitter-cashtag-heatmap/
  • http://ikertxu.tumblr.com/post/56686134143/nodejs-socketio-and-the-twitter-streaming-api

最新更新