a blog for those who code

Wednesday 30 December 2015

Get Latest Reddit posts in Node.js

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.

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 the above code at first we are defining our subreddit (i.e. node). We will be getting all the posts from node subreddit. 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 (json). 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.

5 comments:

  1. Didn't know Reddit had a JSON feed - learnt something new today, thanks!

    ReplyDelete
  2. I'm getting an error when i try to run that code

    undefined:1



    SyntaxError: Unexpected end of JSON input
    at Object.parse (native)
    at IncomingMessage. (C:\Users\user\Bots\Hackerman\reddit creep.js:14:33)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:973:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

    ReplyDelete
  3. Yes guys, you've got to require('httpS') then url of reddit is https://...
    otherwise, it's error!

    ReplyDelete
    Replies
    1. There is no such Module as "httpS"

      Delete