0

With the following code, I'm able to console.log the data that I need for a project. However, given that the data variable is local, I'm having trouble exporting it for use in the global context, so I can use this data in another file in my project. The error is that the 'data' is not defined when console logging this data in the other file. Could somebody explain why the following won't export, and potential resolutions?

var cheerio = require("cheerio")
var request = require("request")
var promise = require("promise")

var data;

request('https://www.numberfire.com/nba/fantasy/full-fantasy-basketball-projections', function (error, response, html) {
  if (!error && response.statusCode == 200) {
    var $ = cheerio.load(html)
    var variable = $('script')[1].children[0].data
    data = variable.substring(variable.indexOf("= ")+2, variable.indexOf(";"))
  }
})

module.exports = data;
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
mkayen
  • 27
  • 5

1 Answers1

0

request is a async function and this code will be run at the time module be required. But when the time code run, data still be undefined.

module.exports = undefined;

And later you can't get private data value by variable pointer.

Before request

module.exports -> undefined

data -> undefined

After request

module.exports -> undefined (it can't point to data variable!!!!)

data -> variable.substring(variable.indexOf("= ")+2, variable.indexOf(";"))

Chen-Tsu Lin
  • 22,876
  • 16
  • 53
  • 63