var redditSubModule = "node";

var http = require('http');





function getRedditPosts() {

var url = "http://www.reddit.com/r/" + redditSubModule + "/new/.json?limit=50";





var request = http.get(url, function(response) {

var json = '';

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

json += chunk;

});





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

var redditResponse = JSON.parse(json);

redditResponse.data.children.forEach(function(child) {

if(child.data.domain !== 'self.node') {

console.log('-------------------------------');

console.log('Author : ' + child.data.author);

console.log('Domain : ' + child.data.domain);

console.log('Title : ' + child.data.title);

console.log('URL : ' + child.data.url);

}

});

})

});

request.on('error', function(err) {

console.log(err);

});

}





getRedditPosts();

In this post we will be discussing about getting latest Reddit posts in Node.js. We will be fetching a listing of all links from a particular subreddit and display that on the console. In the code below we will be getting Reddit posts in a JSON format and parse it in our code.The code extracts Author, Domain, Title and URL. We will be ignoring the "Text Post" as we intended to get only the links posted on Reddit.In the above code at first we are defining our subreddit (i.e. node). We will be getting all the posts fromsubreddit. Then we are calling the Reddit URL with the limit (50 here) which will give us response object. On response object if we have data we will be adding it to our local variable (). Once we get all the data (on response end), we will parse the json and and get result as we want. The output of the above code is shown below :Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.