http.globalAgent(在v0.5.9中添加)属性是‘http’模块的内置属性,该属性用作所有HTTP客户端请求的默认属性。它是Agent的全局实例。
代理会维护对给定主机和端口的未决请求队列,为每个主机和端口重用单个套接字连接,直到队列为空为止,此时套接字或者被销毁,或者被放入池中,以供再次使用。请求到相同的主机和端口。
为了获得响应和正确的结果,我们需要导入‘http’模块。
导入:
const http = require('http');
用法:
http.globalAgent
参数:如上所述,此属性不接受任何参数。
返回值<http.Agent>:它负责管理HTTP客户端的连接持久性和重用。
下面的示例说明在Node.js中使用http.globalAgent属性。
范例1: 文件名:index.js
// Node.js program to demonstrate the
// http.globalAgent Method
// Importing http module
var http = require('http');
const { globalAgent } = require('http');
const PORT = process.env.PORT || 3000;
console.log(globalAgent);
// Creating http Server
var httpServer = http.createServer(
function(request, response) {
console.log(globalAgent);
var Output = "Hello Geeksforgeeks..., "
+ "Output of global agent is:" +
JSON.stringify(globalAgent);
// Prints Output on the browser in response
response.write(Output);
response.end('ok');
});
// Listening to http Server
httpServer.listen(PORT, ()=>{
console.log("Server is running at port 3000...");
});
使用以下命令运行index.js文件:
node index.js
输出:
In Console
>> Server is running at port 3000…
Agent { _events:[Object:null prototype] {
free:[Function (anonymous)],
newListener:[Function:maybeEnableKeylog]}, _eventsCount:2,
_maxListeners:undefined, defaultPort:80,
protocol:‘http:’, options:{ path:null },
requests:{}, sockets:{},
freeSockets:{}, keepAliveMsecs:1000,
keepAlive:false, maxSockets:Infinity,
maxFreeSockets:256, scheduling:‘fifo’,
maxTotalSockets:Infinity, totalSocketCount:0,
[Symbol(kCapture)]:false}
现在在浏览器中运行http://localhost:3000 /。
Output: In Browser
Hello Geeksforgeeks…, global agents are:{“_events”:{}, “_eventsCount”:2, “defaultPort”:80,
“protocol”:”http:”, “options”:{“path”:null}, “requests”:{}, “sockets”:{},
“freeSockets”:{}, “keepAliveMsecs”:1000, “keepAlive”:false, “maxSockets”:null, “maxFreeSockets”:256,
“scheduling”:”fifo”, “maxTotalSockets”:null, “totalSocketCount”:0}ok
相关用法
- Node.js GM charcoal()用法及代码示例
- Node.js GM blur()用法及代码示例
- Node.js GM sharpen()用法及代码示例
- Node.js GM drawLine()用法及代码示例
- Node.js GM drawArc()用法及代码示例
- Node.js GM drawPolyline()用法及代码示例
- Node.js GM drawBezier()用法及代码示例
注:本文由纯净天空筛选整理自vikas_g大神的英文原创作品 Node.js http.globalAgent Property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。