Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - NodeJS http.request not returning data even after specifying return on the 'end' event

Basically I am trying to scrap some data from website and perform the DOM extraction, deletion and updation on a callback function binded to the 'end' event of http.request.

I have returned the data from the 'end' event callback too but it is not receiving in my route callback function. I get undefined there.

Below is the code block:

var scraper = {
    extractEmail: function (directoryName) {
        var result = getDirectory(directoryName);
        if (result !== 404) {
            var protocol = result.https ? https : http;
            protocol.request({
                host: 'somevalue.net',
                method: "GET"
            }, function (res) {
                var data = '';
                res.on('data', function (chunk) {
                    data += chunk;
                });

                res.on('end', function () {
                    return data;
                });
            })
                .on('error', function (err) {
                    return err;
                })
                .end();
            //return data;
        }
        else {
            //return "Failed";
        }
    }
};

And here is the Routes.js function:

app.get('/:directory', function (req, res) {
    var n = scraper.extractEmail(req.params.directory);
    console.log(n);
    res.send(n);
});

In here also I don't get the value of n.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is your 'var scraper' also in the route.js file? I guess it's not and you are unable to access that other js file, for doing so use module.exports.

eg.

// module.js
var name = "foobar";
// export it
exports.name = name; 



Then, in route.js...
>      //route.js
>      // get a reference to your required module
>      var myModule = require('./module'); 
>      //correct path to folder where your above file is
>      // name is a member of myModule due to the export above
>      var name = myModule.name;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...