Pretty new to Node, and I'm trying to implement a twitter stream into my node/express app.
This file is inside a separate stream.js file inside my routes folder, and it's called via ajax from a client side jquery script.
I've looked and compared the http.request on several other sites and I've tried multiple configurations but nothing is budging. Everything up to http.request callback fires, but I can't get a response
var http = require('http')
, events = require('events')
, url = require('url')
, fs = require('fs')
, path = require('path')
, sys = require('sys')
, tweet_emitter = new events.EventEmitter()
, options = {
host: "api.twitter.com",
port: 80,
path: "/1/statuses/public_timeline.json",
method: "GET"
}
var getTweets = function() {
console.log('getTweets');// fires fine
var req = http.request( options, function( res ) {
console.log('STATUS: ' + res.statusCode);// nothing here executes
console.log('HEADERS: ' + JSON.stringify(res.headers));
var data = "";
res.setEncoding('utf8');
res.on('data',function( chunk ) {
data += chunk;
console.log(chunk);
});
res.on('end',function() {
var tweets = JSON.parse( data );
if( tweets.length ) tweet_emitter.emit( 'tweets', tweets )
})
req.end()
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
})
}
setInterval(getTweets, 5000 );
exports.stream = function(req, res){
var listener = tweet_emitter.addListener("tweets", function( tweets ) {
res.writeHead(200, { "Content-Type" : "text/plain" });
res.write( JSON.stringify(tweets) );
res.end();
clearTimeout(timeout);
});
var timeout = setTimeout(function() {
res.writeHead( 200, { "Content-Type" : "text/plain" });
res.write(JSON.stringify([]));
res.end();
tweet_emitter.removeListener(listener);
},10000);
};
I second Steve's comment. So many starting NodeJS developers hack their way on very low level methods that have been built by giants. Check out some of the more common libraries available on NPM.
Consider: https://github.com/joyent/node/wiki/modules or: https://npmjs.org/
Best of luck!