#SayItWithHugs

var https = require('https');

var headers = {

'User-Agent': 'Coding Defined',

Authorization: 'Bearer ' + require('./oauth.json').access_token

};





function jsonHandler(response, callback) {

var json = '';

response.setEncoding('utf8');

if(response.statusCode === 200) {

response.on('data', function(chunk) {

json += chunk;

}).on('end', function() {

callback(JSON.parse(json));

});

} else {

console.log('Error : ' + reseponse.statusCode);

}

};





var trendOptions = {

host: 'api.twitter.com',

path: '/1.1/trends/place.json?id=23424848',

headers: headers

};





var tweetDetails = {

maxresults: 100,

resultType: 'recent',

options: {

host: 'api.twitter.com',

headers: headers,

}

};





function callTwitter(options, callback){

https.get(options, function(response) {

jsonHandler(response, callback);

}).on('error', function(e) {

console.log('Error : ' + e.message);

})

};





function fullTweetPath(query) {

var path = '/1.1/search/tweets.json?q=%23SayItWithHugs';

tweetDetails.options.path = path;

};





callTwitter(trendOptions, function(trendsArray) {

fullTweetPath();

callTwitter(tweetDetails.options, function(tweetObj) {

tweetObj.statuses.forEach(function(tweet) {

console.log('

' + tweet.text);

})

})

});

{"token_type":"bearer","access_token":"<Your_Unique_Access_Token>"}



Then we will create a function called callTwitter() which will show the tweets. When we run the above code we will get the result as :

Before going through the code I strongly recommend you to go through How to fetch trending tweets in Nodejs and Fetching Twitter Trends by places in Node.js which will give you a basic idea of how to get Consumer Key and Consumer Secret Key from Twitter Apps. For this example we have used hashtag :Code :If you go through the above code, we have created a POST request with headers like user-agent, authorization, content-type and content-length. When we are getting a response with the status code of 200 ,we are adding the response to the oauthJsonFile (oauth.json). The oauth.json file will look like belowWe have created a function called jsonHandler() which will receive the response stream and convert JSON to object. Then we have created trendOptions object which will provide settings relevant to the Twitter API. As you can see in the path we have added an Id which is nothing but the places Id of India. The place_id is a place in the world. These IDs can be retrieved fromPlease Like and Share CodingDefined.com Blog, if you find it interesting and helpful.