Node.js request.socket Property
The request.socket (Added in v0.3.0) property is an inbuilt property of the ‘http’ module which references to the underlying socket and most users don’t get access to this property. Particularly, the socket doesn’t emit ‘readable‘ events but, the socket could be accessed via request.connection. This property guarantees to being an instance of the <net.Socket> class, a subclass of <stream.Duplex>.
In order to get a response and a proper result, we need to import ‘http’ module.
const http = require('http');
Syntax:
request.socket
Parameters: This property does not accept any parameters.
Return Value: It returns the request data in the form of an object which contains a huge amount of data related to socket.
- <stream.Duplex>: <stream.Duplex> or duplex stream is a stream that implements both a readable and a writable.
The below examples illustrate the use of request.socket property in Node.js.
Example 1: Filename: index.js
const http = require( 'http' );
const req = http.get({ host: 'www.geeksforgeeks.org' });
req.end();
req.once( 'response' , (res) => {
console.log(req.socket);
console.log(`IP address of geeksforgeeks is
${req.socket.localAddress}.`);
console.log(`Its Port is ${req.socket.localPort}.`);
});
|
Output:
>> <ref *1> Socket{ connecting: false,
_hadError: false,
_parent: null,
_host: ‘www.geeeksforgeeks.org’… [Symbol(kBytesWritten)]: 0 }
>> IP address is 192.168.43.207
>> Its port is 56933.
Example 2: Filename: index.js
const { get } = require( 'http' );
const options = { host: 'www.geeksforgeeks.org' };
const req = get(options);
req.end();
req.once( 'response' , (res) => {
console.log( "Status:" , res.statusCode,
res.statusMessage);
console.log( "Host:" , req.socket._host);
console.log( "Method:" ,
req.socket.parser.outgoing.method);
console.log( "Parser Header:" ,
req.socket.parser.outgoing._header);
console.log( "Writable:" , req.socket.writable);
console.log( "Readable:" , req.socket.readable);
console.log( "Http Header:" ,
req.socket._httpMessage._header);
if (req.socket._httpMessage._header ===
req.socket.parser.outgoing._header) {
console.log( "Both headers are exactly same..." )
} else {
console.log( "Headers are not same..." )
}
console.log(`IP address of geeksforgeeks is
${req.socket.localAddress}.`);
console.log(`Its port is ${req.socket.localPort}.`);
});
|
Run index.js file using the following command:
node index.js
Output:
>> Status: 301 Moved Permanently
>> Host: www.geeksforgeeks.org
>> Method: GET
>> Parser Header: GET / HTTP/1.1
Host: www.geeksforgeeks.org
Connection: close
>> Writable: true
>> Readable: true
>> Http Header: GET / HTTP/1.1
Host: www.geeksforgeeks.org
Connection: close
>> Both headers are exactly same…
>> IP address is 192.168.43.207
>> Its port is 57425.
Reference: https://nodejs.org/api/http.html#http_request_socket
Last Updated :
01 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...