Skip to content
Afa' Afa'

Generate random and available port

Find a free TCP port in Node.js by probing candidates with a temporary server.

1 min read Updated

This Node.js module finds a free TCP port by attempting to listen on candidates and returning the first one that succeeds. It is useful in tests and local tooling where a fixed port would clash. The module is reproduced below.

Generate random and available port using Node.js

Network.mjs

javascript
import net from 'net';

function isUsed(port) {
  return new Promise((resolve) => {
    const server = net.createServer((socket) => {
      socket.write('Echo server\r\n');
      socket.pipe(socket);
    });
  
    server.listen(port, '127.0.0.1');
    server.on('error', () => resolve(true));
    server.on('listening', () => {
      server.close();
      resolve(false);
    });
  });
};

export default {
  async generatePort(min, max) {
    let port;
    let usCurrentlyUsed;

    do {
      port = Math.floor(Math.random() * (max - min + 1) + min);
      usCurrentlyUsed = await isUsed(port);
    } while (usCurrentlyUsed);

    return port;
  },
};
Something wrong or want to discuss this article? Get in touch

Search articles and projects

Type to filter articles and projects. Use the arrow keys to move through results and Enter to open one. Press Escape to close.