nodejs http.request保存在全局variables中

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

有一个例子可以提取一些网页内容,但是如何将内容保存到一个全局variables? 它只访问函数的东西。

如果仔细看看这个例子,那个HTTP请求就被用来将数据发布到一个位置。 为了获取网页内容,您应该使用GET方法。

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

HTTP响应在callback函数中的on事件函数中可用,该函数作为构造函数的参数提供。

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

现在我们已经实现了事件处理程序,调用请求结束来发送请求。

 req.end();