I'm trying to create a function which returns a JSON object from an URL. It should work like this:
function getObject(url) {
// return undefined when the url or json is invalid
return object;
}
So that I can use it in this way, if I would use the following URL:
var object = getObject('http://ip.jsontest.com/');
console.log('My IP is: ' + object.ip)
The JSON from the example looks like this:
{"ip": "127.0.0.1"}
So the code above should log this:
My IP is: 127.0.0.1
I already tried it with the request module and found this example on StackOverflow:
request.get({
url: 'http://ip.jsontest.com/',
json: true,
headers: {'User-Agent': 'request'} }, (err, res, data) => {
if (err) {
console.log('Error:', err)
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode)
} else {
// data is already parsed as JSON:
console.log(data)
}
})
The data is displayed in the console as it should, but I found no way to use the it like in the example I provided above. Is there a way to solve this without callbacks? I read that requests are asynchronous, but I need a synchronus solution.