1

In my example I'm trying to use a variable outside of the function but no luck yet. Guys can you take a look into and help me to solve this issue? I want to use a variable "value" outside of the function.

var https = require('https');
var options = {
  hostname: 'example.com',
  port: 443,
  path: '/values',
  method: 'GET'
};

var req = https.request(options, (res) => {
  console.log('statusCode: ', res.statusCode);
  console.log('headers: ', res.headers);
  res.on('data', (d) => {
    var Array = JSON.parse(d);
    value = Array[0][1];
    console.log(value);
  });
});
req.end();
req.on('error', (e) => {
  console.error(e);
});
elif
  • 5,427
  • 3
  • 28
  • 28
J. Doe
  • 21
  • 1
  • 3
  • By the way, you shouldn't assume the response data will arrive in a single `data` event. It could easily be split across multiple `data` events. You should only parse once on the `end` event. – mscdex Jan 07 '16 at 17:25

1 Answers1

0

There aren't really any tricks or overrides to accomplish this. You have to plan to have both places be able to see the variable in the same scope (you should read about scope in javascript).

Closures and classes can enable you a few other tricks playing with scope, but none that allow you to override the scoping rules entirely.

A "trick" I can think of regarding scope is using window in a browser to get to the global object. This can help you get to a "hidden" variable - one that's in scope but whose name has been overtaken by a local variable (or other variable closer in the scope chain). But again, design your code properly and situations like this won't happen.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75