portfinder

repository·master·Indexed 21 days ago

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

A utility for finding available (unbound) TCP ports or socket file paths on a machine, useful for dynamically assigning ports to servers during development or testing. It provides methods such as getPort, getPortPromise, getPorts, and getSocket, with support for both callback and Promise-based patterns. Users can configure search boundaries globally via setBasePort and setHighestPort, or per-invocation using PortFinderOptions and SocketFinderOptions.

Tokens
1.6K
Snippets
11
Records
11
Agent score
25%

What's inside portfinder

  1. Configure the port search scope

    master

    By default, portfinder searches from port 8000 up to 65535. You can modify this behavior in two ways:

    1. Global Configuration

    Set the search boundaries globally for all subsequent calls using setBasePort and setHighestPort.

    2. Per-invocation Configuration

    Pass an options object directly to getPort to define a specific range for a single request.

    Options object keys:

    • port: The minimum port to start searching from.
    • stopPort: The maximum port to search up to.
    // Global configuration
    portfinder.setBasePort(3000);    // default: 8000
    portfinder.setHighestPort(3333); // default: 65535
    
    // Per-invocation configuration
    portfinder.getPort({
      port: 3000,    // minimum port
      stopPort: 3333 // maximum port
    }, callback);
  2. Find a free port using getPortPromise()

    master

    If you prefer working with Promises, use getPortPromise(). It resolves with the free port or rejects with an error if no free port could be found within the search scope.

    const portfinder = require('portfinder');
    
    portfinder.getPortPromise()
      .then((port) => {
        //
        // `port` is guaranteed to be a free port
        // in this scope.
        //
      })
      .catch((err) => {
        //
        // Could not get a free port, `err` contains the reason.
        //
      });
  3. Find a free port using getPort()

    master

    The getPort method uses a callback pattern to find an available port. The returned port is guaranteed to be free within the configured search scope.

    const portfinder = require('portfinder');
    
    portfinder.getPort(function (err, port) {
      //
      // `port` is guaranteed to be a free port
      // in this scope.
      //
    });
  4. Configure SocketFinderOptions

    master

    When calling getSocket or getSocketPromise, you can pass a SocketFinderOptions object:

    OptionTypeDescription
    modnumberMode to use when creating the folder for the socket if it doesn't exist.
    pathstringThe specific path to the socket file to create. Defaults to ${exports.basePath}.sock if not provided.
    const options: SocketFinderOptions = {
      path: '/tmp/app.sock',
      mod: 0o777
    };
  5. Configure PortFinderOptions

    master

    When calling getPort, getPortPromise, or getPorts, you can pass a PortFinderOptions object to refine the search:

    OptionTypeDescription
    hoststringThe host to find an available port on.
    startPortnumberThe search start port. Note: getPort and getPortPromise mutate port state during recursion, so this ensures the search begins at the intended port.
    portnumberThe minimum port. This takes precedence over basePort.
    stopPortnumberThe maximum port to search up to.
    const options: PortFinderOptions = {
      host: '127.0.0.1',
      port: 3000,
      stopPort: 4000
    };
  6. Find a single available port with getPort()

    master

    Use getPort to find an unbound port on the current machine. It supports three usage patterns:

    1. Promise-based: Returns a Promise<number> when called with an options object.
    2. Callback-only: Returns void and executes a callback with (err, port) => void.
    3. Options + Callback: Returns void and executes a callback after applying the provided PortFinderOptions.

    Note: If you provide an options object, it returns a Promise. If you provide a callback, it uses the callback pattern.

    // Promise usage
    const port = await getPort({ port: 3000 });
    
    // Callback usage
    getPort({ port: 3000 }, (err, port) => {
      if (err) throw err;
      console.log(port);
    });
  7. Find an available socket path with getSocket()

    master

    Use getSocket to find or create an available socket file path. It supports Promise-based usage via getSocketPromise(options) or callback-based usage via getSocket(options, callback).

    Returns a string representing the path to the socket.

    // Promise usage
    const socketPath = await getSocket({ path: '/tmp/my-socket.sock' });
  8. Find multiple available ports with getPorts()

    master

    Use getPorts to retrieve an array of unbound ports. It supports:

    1. Promise-based: getPorts(count, options) returns Promise<Array<number>>.
    2. Callback-based: getPorts(count, callback) or getPorts(count, options, callback).
    3. Promise-specific helper: getPortsPromise(count, options) returns Promise<Array<number>>.
    // Get 5 available ports starting from port 8000
    const ports = await getPorts(5, { port: 8000 });
  9. Configure port search boundaries with setBasePort and setHighestPort

    master

    You can globally define the range of ports that portfinder is allowed to search within using these functions:

    • setBasePort(port: number): Sets the lowest port to begin any port search from. This updates the basePort variable.
    • setHighestPort(port: number): Sets the highest port to end any port search from. This updates the highestPort variable.
    import { setBasePort, setHighestPort } from 'portfinder';
    
    setBasePort(1000);
    setHighestPort(5000);