0

I'm writing a simple program that makes a request to reddit, and gets back the page in JSON format. I do this by appending '.json' to the end of the reddit url. For example, if i wanted to get the page for my profile i would do "www.reddit.com/user/stebon24.json".

Here is my program so far. I will log and describe the error below.

var http = require('http');
var options = {
    host: 'www.reddit.com',
    path: ''
};

module.exports = function(username) {

    console.log(username);

    options.path = '/user/' + username + '.json';

    var userData;

    http.get(options, function(res) { 

        res.on('data', function(data) {
            userData += data;
            console.log(userData);
        });

        res.on('end', function() {
            userData = JSON.parse(userData);
            console.log(userData);
        });
    });
};

As for the error, it happens when the program gets to the point where it needs to run JSON.parse(). I know this because i can see it output the raw JSON from when i log the result on the 'data' event. Then this error is output...

undefined:1
undefined{"kind": "Listing", "data": {"modhash": "", "children": [{"kind": "t1
^
SyntaxError: Unexpected token u
    at Object.parse (native)
    at IncomingMessage.module.exports (/home/stephen/Desktop/karmacrawler/engine/crawlUser.js:23:20)
    at IncomingMessage.EventEmitter.emit (events.js:126:20)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at Socket.socketOnData [as ondata] (http.js:1367:20)
    at TCP.onread (net.js:403:27)

1 Answer 1

1

Remember to set an initial value for userData so that it won't initialize as "undefined":

var userData = '';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.