0

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?

10
  • It's just not possible to do that. Commented Dec 10, 2013 at 23:13
  • It is Async, so you need to make your workflow Async as well... Commented Dec 10, 2013 at 23:14
  • Anything is possible, just add a while loop to block the server until the async call has completed. Commented Dec 10, 2013 at 23:15
  • @adeneo you've got a black heart, you do. Commented Dec 10, 2013 at 23:16
  • @Pointy - Sometimes, I didn't post it as an answer, or say it was a great idea, but I've seen code where people have actually used while loops because they didn't understand how to work with async methods. Commented Dec 10, 2013 at 23:18

1 Answer 1

5

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, I see but would that be possible to do in one function? I'm just curious on how things I should do things in node since I'm new to it
Synchronous code which depends on asynchronous code isn't doable. You can only return values in functions which don't depend on asynchronous code. In an async world, use callbacks.
Okay, so I added a callback and tried something like, var something = getHeaders(webpage, function(err, data, res) { return res.headers; }); Which returned undefined as I thought is their any way I can assign the res.headers to a returnable value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.