Created
May 8, 2012 14:45
-
-
Save woeye/2635782 to your computer and use it in GitHub Desktop.
Using the Twitter Streaming API from node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var https = require('https'), | |
http = require('http'), | |
querystring = require('querystring'); | |
var postData = querystring.stringify({ | |
delimited: 'length', | |
track: '#wow' | |
}); | |
var options = { | |
host: 'stream.twitter.com', | |
path: '/1/statuses/filter.json', | |
method: 'POST', | |
auth: '<username>:<password>', // Please set your credentials here! | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Content-Length': postData.length | |
} | |
}; | |
console.log("Connecting to Twitter streaming API ..."); | |
var req = https.request(options, function(res) { | |
console.log("Connected! Response code: " + res.statusCode); | |
console.log('HEADERS: ' + JSON.stringify(res.headers)); | |
res.setEncoding('utf8'); | |
res.on('data', function(chunk) { | |
var msg = chunk.toString('utf8'); | |
var pos = msg.indexOf("{"); // The object might NOT begin at index 0! | |
msg = msg.substring(pos); | |
//console.log(">>>" + msg + "<<<"); | |
var statusMsg = JSON.parse(msg); | |
//console.log(statusMsg); | |
console.log(statusMsg.user.screen_name + ": " + statusMsg.text); | |
}); | |
}); | |
req.on('error', function(e) { | |
console.error(e); | |
}); | |
req.write(postData); | |
req.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment