agent.maxFreeSockets Method in Node.js
0 223
Introduction to agent.maxFreeSockets
In Node.js, the agent.maxFreeSockets
property is part of the http.Agent
class, introduced in version v0.11.7. It defines the maximum number of sockets that should be kept open in a free (idle) state per host. This setting is particularly useful when the keepAlive
option is enabled, allowing for persistent connections and efficient reuse of sockets.
Default Behavior
By default, agent.maxFreeSockets
is set to 256. This means that, when keepAlive
is true, the agent will maintain up to 256 idle sockets per host. If the number of idle sockets exceeds this limit, older sockets will be closed to free up resources.
Setting agent.maxFreeSockets
You can customize the number of free sockets by setting the maxFreeSockets
property when creating a new agent:
const http = require('http');
const agent = new http.Agent({
keepAlive: true,
maxFreeSockets: 10
});
In this example, the agent is configured to keep a maximum of 10 idle sockets per host.
Using the Agent in HTTP Requests
Once the agent is configured, you can use it in HTTP requests to manage connections:
const options = {
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET',
agent: agent
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
});
req.end();
This setup ensures that the specified number of idle sockets are maintained, optimizing connection reuse and resource management.
Conclusion
The agent.maxFreeSockets
property in Node.js provides fine-grained control over the number of idle sockets maintained per host. By adjusting this setting, developers can optimize resource usage and improve the performance of applications that make frequent HTTP requests.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments