Skip to content

Instantly share code, notes, and snippets.

@tpaschalis
Forked from edds/README.md
Last active March 6, 2018 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tpaschalis/a29ca9f986ea8c0c19e94c866a2f66ab to your computer and use it in GitHub Desktop.
Save tpaschalis/a29ca9f986ea8c0c19e94c866a2f66ab to your computer and use it in GitHub Desktop.
Stream tweets containing a specific hashtag to your browser, using Socket.io

A simple example to create a websocket server and stream tweets of a specific hashtag to your browser.

Setup

$ sudo npm install socket.io 
$ sudo npm install twitter

Get your Standard Twitter API credentials from https://apps.twitter.com/ .
Make sure to include any valid URL (eg. https://www.google.com) as the Callback URL, so that the keys can work as a browser app.

Run

$ node ./app.js

Then open http://localhost:1337/ in your browser.

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(full_project_directory_ + '/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: '#survivorgr' }, function(stream) {
stream.on('data', function (data) {
io.sockets.emit('tweet', data.text);
console.log('.');
});
});
<!doctype html>
<title>Twitter Stream</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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment