简体   繁体   中英

JavaScript use local variable globally

var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');

var link = "www.google.com";

request(link, function (error, response, html) {

    if (!error && response.statusCode == 200) {

        var $ = cheerio.load(html);

        //scrape article
        $('.someclass').filter(function () {

            var data = $(this);
            var description = data.html();

            //write data to file
            fs.appendFile('description.txt', description + "\n", function (err) {
                if (err)
                    throw err;
                //console.log('The "description" was appended to file!');
            });

        })

    }
});

I am using this code in my node.js to get some data. But I want to use the variable description globally (outside of the request procedure). I've tried with return and it didn't work. How to do this?

Edit: This is another question that I asked. This question and question above are giving me same problems. Solving one of them or both will help a lot.

node.js multiple functions within request

Would placing the description variable outside the request function with a dummy value work? Such as:

var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');

var link = "www.google.com";
var description="placeholder";
request(link, function (error, response, html) {
...

            description = data.html();
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM