0

I'm trying to write a function in JS which can return me the text I've got from https.get request.

I've found this code to display the text I want :

const https = require('https')

https.get('http://mysiteweb.com/info', (resp) => {
  let data = ''

  let value = ''


  // A chunk of data has been recieved.

  resp.on('data', (chunk) => {
    $data += chunk;
  })

  // The whole JSON response has been received, get the "value"
  resp.on('end', () => {
    value = JSON.parse(data).value
  // print the text I want to return
  console.log(value)
  })
})

But purpose is to write a function which returns me the "value" depending the url I put. Something like :

function getValueFromUrl(url) {
// code on top to get "value"
 return value }

But I can't access to "value" after all the tries I've done to return it. How can I do that ? I'm new in JS. Thanks a lot

1 Answers1

0

Because the HTTP call is asynchronous you can't simply return the value, you need to provide a callback that will be called after the request is completed.

const https = require('https')

function getValueFromUrl(url, cb) {
  https.get(url, (resp) => {
    let data = ''

    let value = ''

    resp.on('data', chunk => data += chunk);

    resp.on('end', () => {
      value = JSON.parse(data).value

      cb(null, value);
    });
  }).on('error', (err) => {
    cb(err);
  });
}

getValueFromUrl('http://mysiteweb.com/info', (err, value) => {
    if (err) return console.error(err);

    console.log(value);
});

Alternatively you can use Promises or await/async instead of callbacks.

hugomarisco
  • 326
  • 2
  • 9