Getting the port number from the service name

25 views
Skip to first unread message

Jean Marie

unread,
Mar 21, 2018, 12:49:35 PM3/21/18
to nodejs
Hello

I use the method createServer from class http and then listen to a port as follows :

var server = http.createServer();
  server
.listen(port, function () {
 
...
}

the problem is that I only have the service name 
and  listening to a service doesn't work :

var server = http.createServer();
  server
.listen(service, function () {
 
...
}


so I need to read and parse the file /etc/services to get the port associated with the service 

is there a simpler way to get the port from the service ?

thanks in advance

Jean-Marie

Mikkel Wilson

unread,
Mar 28, 2018, 3:06:51 PM3/28/18
to nodejs
So, a 'service' is a logical human thing, not a fixed, networking thing. The items in /etc/services are just a handy 'commonly used' mapping, but aren't strictly or adhered to or used to configure the applications on your host. You can listen to HTTP on port 1337 just as well as you can on port 80 (with proper permissions). You can get the ports that a *currently running* process is using, but I don't think that helps you. 

It seems you're trying to listen to a port and respond with HTTP traffic. A common pattern to dynamically choose the port to listen to is with environment variables.

var server = http.createServer();
  server
.listen(process.env.PORT, function () {
 
...
}

And then start the application by specifying the port on the command line:

$ PORT=1337 node server.js

This lets you change the port easily without modifying the code or run multiple copies of your server listening to different ports at the same time.

HTH,
Mikkel
Reply all
Reply to author
Forward
0 new messages