k.ueckermann
k.ueckermann

Reputation: 73

Recreate http request and response from active Socket in Node js

I am creating a system that passes http request to a child process in Node js. I cant pass the child process the active Socket using child.send( 'socket', req.socket ) but inside the child I want to recreate the http request and response objects so that they have the headers, parameters, cookies etc.

I am using Express, so if I can recreate the Express req and res object it's even better.

I have been fiddling a bit, but no success. If I do the following it creates the IncomingMessage object but the headers etc are empty.

var http = require('http');

/* Child Process recieves the Socket  */

var incomingMessage = new http.IncomingMessage( socket );

Any ideas if there is any way to accomplish what I want?

Upvotes: 2

Views: 645

Answers (1)

FishExplosion
FishExplosion

Reputation: 11

You can also this trick for tunneling:

let agent;
if (protocol == 'https:')
    agent = new https.Agent();
else
    agent = new http.Agent();
agent.createConnection = (opts, callback) => callback(false, socket);

const req = http.request({
    method: method,
    host: host,
    port: port,
    protocol: protocol,
    path: path,
    headers: headers,
    agent: agent
}, function (res)
{
    console.log(res.headers);
    console.log(res.socket.remoteAddress);
    console.log(res.socket == socket); // true
});
req.end();

Upvotes: 0

Related Questions