Javascript tips
Using Node.js and Twitter Stream API
May 30, 2013
2

Hello folks,

I know I don’t have a frequent blogging experience, but  my second son just arrived and being a dad is not so easy so, I didn’t have too much time to write.

During the small amount of time left , I tried out Node.js a powerful platform built on Chrome JavaScript’s runtime, which lets you write some nice realtime and scalable web application.

For this example you will also need Socket.io and ntwitter a nice Node.js plugin to access Twitter API.

Before starting coding, you will also need an application key from Twitter; key that can be obtained from twitter dev or setting up a new web app with which you can set up the API simply using these lines of  JavaScript:

var twitter = require('/your path to folder/ntwitter'),

// Twitter Setup
module.exports.twit = new twitter({
  consumer_key: 'your key',
  consumer_secret: 'your secret',
  access_token_key: 'your token',
  access_token_secret: 'your token secret'
});

Save them in a file and remember to include this file afterwards, when you will create your Node.js/socket.io server.

To create a simple server which listen to your requests and  uses Twitter stream api, all you have to do is:

var app = require('http').createServer();
var routes = require('/yourpath/node-v0.8.4/node_modules/routes')
  , io = require('/yourpath/node-v0.8.4/node_modules/socket.io').listen(app)
  , twitter = require('/yourpath/node-v0.8.4/node_modules/ntwitter')
  , util = require('util')
  , twitterModule = require('/yourpath/node-v0.8.4/yourpathto/twitterModule');

app.listen(8080)
io.sockets.on('connection', function(socket) {
    console.log('Connected to the server');
    socket.on('filters', function(msg){
	console.log('Received message :'+msg);
	var twit = twitterModule.twit;
	twit.stream('statuses/filter', {'track':msg},
	function(stream) {
		stream.on('data',function(data){
		socket.emit('twitter',data);
        });
     });
    });
    socket.on('disconnect', function () {
       console.log('User disconnected');
       socket.disconnect();
       io.sockets.emit('user disconnected');
    });
})

Looking at the code, is it possible to see that also the file which contains your secret key has been included,  otherwise it wouldn’t have been possible to use Twitter API. Now you can start this small server by opening your shell and type:

node yourservername.js

If everything went in the right direction, you should see something like:

info  - socket.io started

Et voilà, your first small twitter server is up and listening on port 8080.

Ok, now this has been a good exercise but without anything on client side is completely useless. The next step is to create a simple html form with some JavaScript that calls the server.

At first you need to connect to the server:

//define where you want to connect
var socket = io.connect('http://localhost:8080');

//use this function to connect to the server
function connect(){
// Add a connect listener
    socket.on('connect',function() {
      //feedback using JavaScript console
       console.log('Client has connected to the server!');
    });
}
//this functions sends your search to the server
function sendMessage(filter){
    socket.emit('filters',filter);
}
//function which listens to server response
function listen(){
    socket.on('twitter', function (data) {
         console.log(data);
        //do your stuff here with response data
        socket.emit('my other event', { my: 'data' });
      });

}

When you completed everything, you will have a working example of a “real-time” web page, listening to Twitter stream API.

Complete code twitterTrends

Leave a Reply

2 comments

  1. Here is what I’ve built with Twitter Streaming API and Node.js (and ntwitter): http://snapkite.com – search engine for mobile photos posted on Twitter.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close