2

We are developing a WebSocket server using Nodejs with socket.io

I have used createServer method from class HTTP and then listen to a port as follows :

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

Now 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 as follows :

var str = fs.readFileSync(filename).toString();
var serviceline = str.match( port+".*tcp" );
var port = serviceline[0].match( "[0-9]+" )

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

Thanks in advance

Jean-Marie

Ajay P.
  • 455
  • 1
  • 6
  • 14
Jean-Marie
  • 21
  • 1
  • Try with this : console.log('Listening on port ' + server.address().port); – Priyank Mar 23 '18 at 10:30
  • Possible duplicate of [NodeJS: How to get the server's port?](https://stackoverflow.com/questions/4840879/nodejs-how-to-get-the-servers-port) – Evhz Mar 23 '18 at 12:13

2 Answers2

1

You can use find-process to find port from process or vice-versa

Command line usage

npm install find-process -g

Usage: find-process [options] <keyword>


Options:

    -V, --version      output the version number
    -t, --type <type>  find process by keyword type (pid|port|name)
    -p, --port         find process by port
    -h, --help         output usage information

Examples:

    $ find-process node          # find by name "node"
    $ find-process 111           # find by pid "111"
    $ find-process -p 80         # find by port "80"
    $ find-process -t port 80    # find by port "80"

Code usage

npm install find-process --save

const find = require('find-process');

find('pid', 12345)
  .then(function (list) {
    console.log(list);
  }, function (err) {
    console.log(err.stack || err);
  })

I have used this to find process from the port but I think it provides a reverse way to or you can skim down to its repo and pick the code you needed.

Ridham Tarpara
  • 5,970
  • 4
  • 19
  • 39
0

I don't need a server port but the port corresponding to a service name
for instance having the following service "wsgw" specified in file /etc/services

wsgw      8001/tcp               # websocket gateway

I need to get the value 8001 before running the server listening to this port this way :

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

listening to a service as below doesn't work :

var server = http.createServer();
server.listen("wsgw", function () {
...

note : finding a port from a process doesn't help me as it is not a process but a service

Jean-Marie
  • 21
  • 1