Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Creating an Agent in Node.js
In Node.js, an HTTP Agent manages connection pooling for HTTP client requests. You can create a custom agent using the new Agent() constructor to control connection behavior like keep-alive settings and socket limits.
Syntax
new http.Agent({options})
Parameters
The Agent constructor accepts an options object with the following configurable properties:
-
keepAlive - Keeps sockets open for reuse instead of closing them after each request. Default:
false -
keepAliveMsecs - Initial delay for TCP keep-alive packets when
keepAliveis true. Default:1000 -
maxSockets - Maximum number of sockets allowed per host. Default:
Infinity -
maxTotalSockets - Total sockets allowed across all hosts. Default:
Infinity -
maxFreeSockets - Maximum free sockets to keep open. Default:
256 -
scheduling - Strategy for selecting free sockets:
'fifo'or'lifo' -
timeout - Socket timeout in milliseconds
Example: Basic Agent Creation
// Node.js program to demonstrate Agent creation
const http = require('http');
// Creating a basic agent
const basicAgent = new http.Agent({});
// Creating an agent with keep-alive enabled
const keepAliveAgent = new http.Agent({
keepAlive: true,
maxSockets: 5,
keepAliveMsecs: 2000
});
console.log('Basic Agent created:', typeof basicAgent);
console.log('Keep-alive Agent created:', typeof keepAliveAgent);
console.log('Keep-alive enabled:', keepAliveAgent.keepAlive);
console.log('Max sockets:', keepAliveAgent.maxSockets);
Basic Agent created: object Keep-alive Agent created: object Keep-alive enabled: true Max sockets: 5
Example: Making HTTP Request with Custom Agent
const http = require('http');
// Create agent with specific configuration
const customAgent = new http.Agent({
keepAlive: true,
maxSockets: 3,
timeout: 5000
});
// Request options using custom agent
const options = {
hostname: 'httpbin.org',
port: 80,
path: '/get',
method: 'GET',
agent: customAgent
};
// Make HTTP request
const req = http.request(options, (res) => {
console.log('Status Code:', res.statusCode);
console.log('Agent keep-alive:', req.agent.keepAlive);
console.log('Max sockets:', req.agent.maxSockets);
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Response received successfully');
});
});
req.on('error', (error) => {
console.log('Request error:', error.message);
});
req.end();
Status Code: 200 Agent keep-alive: true Max sockets: 3 Response received successfully
Agent vs Global Agent
| Feature | Global Agent | Custom Agent |
|---|---|---|
| Keep-alive | Disabled by default | Configurable |
| Socket limits | Default settings | Customizable |
| Shared across requests | Yes | Only if explicitly reused |
Common Use Cases
Connection pooling - Reuse connections for better performance
Rate limiting - Control concurrent connections per host
Timeout management - Set custom timeout values
Resource optimization - Manage socket usage efficiently
Conclusion
Custom HTTP Agents in Node.js provide fine-grained control over connection management. Use them to optimize performance through connection pooling and to manage resource usage in high-traffic applications.
