Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js http: create persistent connection to host and sending request to several paths

Tags:

http

node.js

I would like to create persistent http connection to host (api.development.push.apple.com) and send POST requests for many paths (for example, '/3/device/1', '/3/device/2', etc.). Will code below create one connection with host or many connections for each http.request()?

var http = require('http');

http.request({
    host: 'api.development.push.apple.com',
    port: 443,
    path: '/3/device/1',
    method: 'POST',
}).end();

http.request({
    host: 'api.development.push.apple.com',
    port: 443,
    path: '/3/device/2',
    method: 'POST'
}).end();
like image 816
yaahor Avatar asked Mar 12 '23 14:03

yaahor


1 Answers

What you want is to use the same Agent for all of your requests.

If you don't specify an agent in the options object, the http module will use the globalAgent, which sets keepAlive to false by default.

So, create your agent, and use it for all requests:

var http = require('http');
var agent = new http.Agent({ keepAlive: true }); // false by default

http.request({
    host: 'api.development.push.apple.com',
    port: 443,
    path: '/3/device/1',
    method: 'POST',
    agent: agent, // use this agent for more requests as needed
}).end();
like image 53
Eli Zehavi Avatar answered Apr 06 '23 23:04

Eli Zehavi