Newb working through Node.js in 24 Hours. This challenge comes from Chapter 15 on JSON API's.
The original code:
var http = require('http')
, data = ""
, tweets = "";
var options = {
protocol: 'http:'
, host: 'search.twitter.com'
, port: 80
, path: '/search.json?q=%23node.js'
};
var request = http.get(options, function(res) {
res.on('data', function(chunk){
data += chunk;
});
res.on('end', function() {
tweets = JSON.parse(data);
console.log(tweets);
for (var i= 0; i< tweets.results.length; i++) {
console.log(tweets.results[i].text)
}
});
res.on('errors', function(e){
console.log("There was an error: " + e.message)
});
});
My question concerns 'res.on(...)'. What I think this means is that when the Twitter server responds with a string, 'data', then perform the function. But I read through the Twitter API (v1 - https://dev.twitter.com/docs/api/1) and didn't see anything that supports that belief. So how exactly does res.on(...) work? TIA for any guidance.
res is a NodeJS event emitter, and res.on hooks up a callback for an event. The object res that you are using is a Node http response object, and it has nothing to do with the REST API that Twitter provides. The Node client makes a request to a http server (be it Twitter or Google or Stackoverflow). When the server responds, the res object emits the corresponding events.
You can try
, host: 'stackoverflow.com',
, port: 80,
, path: '/questions/18149079/nodejs-and-twitter-api-1-res-on-function'
and
res.on('end', function() {console.log(data)});
and check out the resulting html data :P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With