Node.js http.globalAgent 属性
http.globalAgent (在 v0.5.9 中添加)属性是“http”模块的内置属性,用作所有 HTTP 客户端请求的默认值。它是代理的全局实例。
代理维护给定主机和端口的待处理请求队列,为每个请求重用单个套接字连接,直到队列为空,此时套接字要么被销毁,要么被放入一个池中,以便再次使用请求相同的主机和端口。
为了得到响应和正确的结果,我们需要导入' 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
参考: https://nodejs.org/api/http.html#http_http_globalagent