user1228306
user1228306

Reputation: 23

nodejs http.request save in global variable

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.

Upvotes: 2

Views: 4295

Answers (1)

supertopi
supertopi

Reputation: 3488

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();

Upvotes: 4

Related Questions