0

This has been getting to me for a while. So, I am trying to create a function that uses request and returns body of the request, using the request node module. Here is my code:

req = require("request")
foo = req("https://www.youtube.com", function(err, resp, body){
    bar = body
})
console.log(bar)

This, sadly, returns ReferenceError: bar is not defined Anyone able to help? Please test your answer before you post it, because I have tried almost EVERYTHING I can think of.

TigerGold
  • 163
  • 1
  • 7
  • you have to initialize every variable with `var`: `var bar;` `var foo = ... { bar = body }` `console.log(bar);` – Slavik Mar 19 '16 at 12:04
  • logging `bar` outside the `req` function will return nothing especially considering bar has not been defined. Do you get the same result when log `bar` after `bar = body;`? – AVDW Mar 19 '16 at 12:07
  • but you have asynchronous call, so `console.log(bar)` anyway prints 'undefined' – Slavik Mar 19 '16 at 12:07
  • Slavik: I already tried that. AVDW: It works, but that is not what I wanted. – TigerGold Mar 19 '16 at 21:58

2 Answers2

0

Try this:

var request = require("request")
request("https://www.youtube.com", function(err, resp, body){
    bar = body;
    console.log(bar);
});
Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
0

ofcourse it well return ReferenceError: bar is not defined because bar it define only inide the req and also your console.log should be inside the req

req = require("request")
foo = req("https://www.youtube.com", function(err, resp, body){
    var bar = body;
    console.log(bar);
})
elreeda
  • 4,525
  • 2
  • 18
  • 45
  • I know why, I just do not know how to do it. Also, the code above will be in a function that returns the value bar. – TigerGold Mar 19 '16 at 21:57