0

I have written a small code snippet to fetch a quote from the third party service -

var http = require("https");

function getRandomQuote()
{
var returnJson = {};
var options = {
    "method": "GET",
    "hostname": "talaikis.com",
    "port": null,
    "path": "/api/quotes/random/",
};

http.get(options, function(resp){
    resp.on('data', function(chunk){
        console.log("Quote string - "+chunk.toString('utf8'));
        returnJson = JSON.parse(chunk.toString('utf8'));
        console.log(returnJson);
        return returnJson;
    });
   resp.on("error", function(e){
       console.log("Got error: " + e.message);
  });
});

}
var x = getRandomQuote();
console.log(x);

The output is -

{}
Quote string - {"quote":"Such an arrangement would provide Taiwan and China with a forum for dialogue whereby they may forge closer ties based on mutual understanding and respect, leading to permanent peace in the Taiwan Strait.","author":"Nick Lampson","cat":"respect"}
{ quote: 'Such an arrangement would provide Taiwan and China with a forum for dialogue whereby they may forge closer ties based on mutual understanding and respect, leading to permanent peace in the Taiwan Strait.',author: 'Nick Lampson',cat: 'respect' }

Although the correct output is received it isnt returned in the function. How do I fix this?

Prateek Narendra
  • 1,837
  • 5
  • 38
  • 67

1 Answers1

0

I think the problem with your code is that you try to parse each chunk, but basically, you receive invalid JSON objects. Try modifying your code this way:

const http = require("https");

function getRandomQuote()
{
  let returnJson = {};
  const options = {
    "method": "GET",
    "hostname": "talaikis.com",
    "port": null,
    "path": "/api/quotes/random/",
  };

  http.get(options, function(resp){
    let result = "";
    resp.on('data', function(chunk){
      result += chunk;
    });
    resp.on('end', function(chunk) {
      result += chunk;
      returnJson = JSON.parse(result.toString('utf-8'));
      console.log('Result:');
      console.log(returnJson);
    });
  }).on("error", function(e){
    console.log("Got error: " + e.message);
  });
}


const x = getRandomQuote();
// this will fire 'undefined'
console.log(x);
Lazyexpert
  • 3,106
  • 1
  • 19
  • 33