2

In http://nodejs.org/docs/v0.4.7/api/http.html#http.request

There is an example that fetches some web content, but how does it save the content to a global variable? It only accesses stuff the function.

1 Answer 1

4

If look closely at the example, that HTTP request is used to POST data to a location. In order to GET web content, you should use the method GET.

var options = {
    host: 'www.google.com',
    port: 80,
    method: 'GET'
};

The HTTP response is available in the on-event function inside the callback-function which is provided as the parameter for the constructor.

var req = http.request(options, function(res)
{
    res.setEncoding('utf8');
    var content;
    res.on('data', function (chunk)
    {
      // chunk contains data read from the stream
      // - save it to content
      content += chunk;
    });

    res.on('end', function()
    {
      // content is read, do what you want
      console.log( content );
    });
});

Now that we have implemented the event handlers, call request end to send the request.

req.end();
Sign up to request clarification or add additional context in comments.

2 Comments

You just saved me. I was messing around in my code while saving the chunk. Thanks a lot!
@aniskhan001 happy to help :)

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.