A simple example to create a websocket server and stream tweets about a pre-defined subject to the page.
$ npm install socket.io, twitter
$ node ./app.js
Then open http://localhost:1337/
in a browser that supports websockets (or iDevice).
var app = require('http').createServer(handler), | |
io = require('socket.io').listen(app), | |
fs = require('fs'), | |
sys = require('sys'), | |
twitter = require('twitter'); | |
app.listen(1337); | |
var twit = new twitter({ | |
consumer_key: 'CONSUMER_KEY', | |
consumer_secret: 'CONSUMER_SECRET', | |
access_token_key: 'ACCESS_TOKEN_KEY', | |
access_token_secret: 'ACCESS_TOKEN_SECRET' | |
}); | |
function handler (req, res) { | |
fs.readFile(__dirname + '/index.html', | |
function (err, data) { | |
if (err) { | |
res.writeHead(500); | |
return res.end('Error loading index.html'); | |
} | |
res.writeHead(200); | |
res.end(data); | |
}); | |
} | |
var twee = io.of('tweet'); | |
twit.stream('statuses/filter', { track: 'javascript' }, function(stream) { | |
stream.on('data', function (data) { | |
io.sockets.emit('tweet', data.text); | |
console.log('.'); | |
}); | |
}); |
<!doctype html> | |
<title>Socket.io Demo</title> | |
<div id="tweets"></div> | |
<script src="/socket.io/socket.io.js"></script> | |
<script> | |
var socket = io.connect('/'), | |
tweets = document.getElementById('tweets'); | |
socket.on('tweet', function (data) { | |
tweets.innerHTML = tweets.innerHTML + '<br>' + data; | |
}); | |
</script> |
@PterPmnta It's the directory in which your app.js
file is
What does line 29 do?
var twee = io.of('tweet');
I don't see twee used anywhere else.
I tried this code...it doesn't seem to work for me. When I change the console.log in app.js and make it display the incoming text (data.text) it shows correctly in the shell, but it does not get passed to the HTML page. Does this work for anyone else, if so how did you make it work?
Sorry, what path is
__dirname
??