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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。