Nodejs random free tcp ports

My project need to setup a new port every time a new instance of my class is instantiated.

In Node.js how I can find a free TCP port to set in my new socket server? Or check if my specified port is already used or not.


Solution 1:

You can bind to a random, free port assigned by the OS by specifying 0 for the port. This way you are not subject to race conditions (e.g. checking for an open port and some process binding to it before you get a chance to bind to it).

Then you can get the assigned port by calling server.address().port.

Example:

var net = require('net');

var srv = net.createServer(function(sock) {
  sock.end('Hello world\n');
});
srv.listen(0, function() {
  console.log('Listening on port ' + srv.address().port);
});

Solution 2:

For Express app:

const app = require('express')();

const server = app.listen(0, () => {
  console.log('Listening on port:', server.address().port);
});

Solution 3:

To find an opened TCP's port you can use the module portastic

You can find a port like this:

port = require('portastic');

options = {
    min : 8000,
    max : 8005
}

port.find(options, function(err, data){
    if(err)
        throw err;
    console.log(data);
});

Solution 4:

Port Finder Library:

https://github.com/http-party/node-portfinder

I suggest you use portfinder library, it has over 10 million downloads in a week.

By default portfinder library will start searching from 8000 and scan until the maximum port number (65535) is reached.

const portfinder = require('portfinder');

portfinder.getPort((err, port) => {
    //
    // `port` is guaranteed to be a free port
    // in this scope.
    //
});