Nodejs random free tcp ports

I use this compact form:

import net from "net"

async function getPortFree() {
    return new Promise( res => {
        const srv = net.createServer();
        srv.listen(0, () => {
            const port = srv.address().port
            srv.close((err) => res(port))


const PORT = await getPortFree()

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.


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);

For Express app:

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

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