Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the port number in node.js when a request is processed?

Tags:

node.js

If I have two node.js servers running, how can I tell which server called the processRequest function?

var http = require('http');
var https = require('https');
function processRequest(req, res) {
    res.writeHead(200);
    res.end("hello world, I'm on port: " + ???.port + "\n");
}
var server1 = http.createServer(processRequest).listen(80);
var server2 = https.createServer(processRequest).listen(443);

Originally I wanted the port number, but couldn't find the object/variable to give it to me. Based on the below answer it makes more sense to determine encrypted vs non-encrypted since the point is to know which of the http servers the request came in on.

like image 733
ciso Avatar asked Apr 27 '14 03:04

ciso


People also ask

What is process env port || 3000?

env. PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there. So you pass that to app. listen , or to app. set('port', ...) , and that makes your server able to accept a "what port to listen on" parameter from the environment.

How the request is processed in NodeJS?

The first one runs only once since it is a synchronous method. The * get route is not setup until after it returns. The second will run when any http request comes to the server. And yes, it will block the whole server for the duration of that synchronous call (I/O cost to open and read the contents of the file).


Video Answer


2 Answers

The req parameter is an instance of IncomingMessage from which you can access the socket.

From there you can access both the localPort and remotePort.

Something like:

console.log(req.socket.localPort);
console.log(req.socket.remotePort);
like image 102
dc5 Avatar answered Sep 20 '22 01:09

dc5


This way you get the port number:

var http = require('http');
var server = http.createServer().listen(8080);

server.on('request', function(req, res){
    res.writeHead(200, {"Content-Type": "text/html; charset: UTF-8"});
    res.write("Hello from Node! ");
    res.write(" Server listening on port " + this.address().port);
    res.end();
});
like image 42
johannesMatevosyan Avatar answered Sep 19 '22 01:09

johannesMatevosyan