0

I'm using request and Node JS to get source code from a webpage and stock it in a variable in order to work on it after.

var request = require('request');
var htmldata="";
request('https://www.nba.com', function (error, response, body) {
  htmldata=body;
});
console.log(htmldata);

I want the variable htmldata to get the value of the parameter of the function body which contains the source code but it returns me a blank string.

I thank you in advance if you resolve my problem

1 Answers1

-2

Place console.log inside the function.

var request = require('request');
var htmldata="";
request('https://www.nba.com', function (error, response, body) {
  htmldata=body;
  console.log(htmldata);
});

Put the console.log inside the callback function because javascript is async and the request method takes time, so by the time console.log runs, the request method has not completed its call yet. – thanks @ Mohammad Ganji

  • Ok but how can I work with my variable after this instruction ? – Alexandre G Nov 07 '17 at 22:02
  • you better complete your answer, add a little more description, like he should put the console.log inside the callback function because javascript is async and the request method takes time, so by the time console.log runs, the request method has not completed its call yet. – ganjim Nov 07 '17 at 22:02
  • 1
    you can work with it inside the callback function, or you can make your request function to return a promise and when the promise is fulfilled, you can then use your variable – ganjim Nov 07 '17 at 22:03
  • outside of the function you can test for htmldata for content. – Developer Nodejs Nov 07 '17 at 22:04
  • Thank you for your answers, I will work inside the callback function – Alexandre G Nov 07 '17 at 22:36