ruler
ruler

Reputation: 623

understanding node.js callback

I'm using urllib to make a request to a webpage and I'm trying to return it's headers like so:

var getHeaders = function(webpage){
    var info = urllib.request(webpage, {}, function(err, data, res){
        // console.log(res.headers); works fine and shows them
        return res.headers; // I thought it should make the info variable have the headers information
    }); 
    return info; 
}

Now when I try to get the headers like maybe set-cookie of a webpage I intended it to return the that from the website but it doesn't, so is there a way to return the headers or is it just not possible to do that?

Upvotes: 0

Views: 78

Answers (1)

bevacqua
bevacqua

Reputation: 48566

In Node pretty much everything is done asynchronously, so you'll just need your function to be asynchronous.

var getHeaders = function (webpage, done) {
    urllib.request(webpage, {}, function(err, data, res){
        done(err, res.headers);
    });  
}

The traditional pattern is to use callbacks that return an error as the first argument (or a falsy value in case everything went well), and whatever you need to return afterwards.

Consuming the method is then very similar to what you had to do with the urllib thing.

getHeaders(webpage, function (err, headers) {
    if (err) {
        throw err; // or, you know, deal with it.
    }
    console.log(headers);
});

Upvotes: 5

Related Questions