or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdport-detection.mdport-waiting.md
tile.json

port-detection.mddocs/

Port Detection

Core port detection functionality that automatically finds available network ports. The system intelligently checks multiple network interfaces and suggests alternative ports when the requested port is occupied.

Capabilities

Detect Port Function

The main function for detecting available ports with flexible input options and dual API support (Promise/callback).

/**
 * Detects an available port starting from the specified port
 * @param port - Port number, string, or configuration object. If omitted, returns random port
 * @returns Promise resolving to available port number
 */
function detectPort(port?: number | PortConfig | string): Promise<number>;

/**
 * Detects an available port using callback pattern
 * @param callback - Callback function receiving error and port number
 */
function detectPort(callback: DetectPortCallback): void;

/**
 * Detects an available port with port specification and callback
 * @param port - Port number, string, or configuration object
 * @param callback - Callback function receiving error and port number
 */
function detectPort(port: number | PortConfig | string | undefined, callback: DetectPortCallback): void;

Usage Examples:

import { detectPort } from "detect-port";

// Promise-based usage
const port1 = await detectPort();           // Random available port
const port2 = await detectPort(3000);       // Check port 3000, get alternative if occupied
const port3 = await detectPort("8080");     // String port numbers supported

// Callback-based usage
detectPort(3000, (err, port) => {
  if (err) {
    console.error("Error detecting port:", err);
    return;
  }
  console.log("Available port:", port);
});

// Random port with callback
detectPort((err, port) => {
  console.log("Random available port:", port);
});

Detect Alias

Convenience alias for the detectPort function, providing the same functionality with a shorter name.

/**
 * Alias for detectPort function - same signatures and behavior
 */
const detect: typeof detectPort;

Usage Examples:

import { detect } from "detect-port";

// Same functionality as detectPort
const port = await detect(3000);
console.log(`Available port: ${port}`);

Advanced Configuration

For more control over port detection, use the configuration object approach.

/**
 * Configuration object for port detection
 */
interface PortConfig {
  /** Port number to start checking from */
  port?: number | string;
  /** Specific hostname/IP to bind to during port checking */
  hostname?: string | undefined;
  /** Callback function for callback-based usage */
  callback?: DetectPortCallback;
}

/**
 * Callback function type for port detection
 */
type DetectPortCallback = (err: Error | null, port?: number) => void;

Usage Examples:

import { detectPort, PortConfig } from "detect-port";

// Test port availability on specific hostname
const config: PortConfig = {
  port: 3000,
  hostname: "127.0.0.1"
};

const availablePort = await detectPort(config);
console.log(`Available port on 127.0.0.1: ${availablePort}`);

// With callback in config
const configWithCallback: PortConfig = {
  port: 8080,
  hostname: "localhost",
  callback: (err, port) => {
    if (err) {
      console.error("Detection failed:", err);
      return;
    }
    console.log(`Available port on localhost: ${port}`);
  }
};

detectPort(configWithCallback);

Port Detection Algorithm

The detection process follows a systematic approach:

  1. Start Port: Begin with specified port (or random if none provided)
  2. Port Range: Check up to 10 ports incrementally (port, port+1, port+2, etc.)
  3. Network Interface Testing: For each port, test availability on:
    • Default interface (null/undefined hostname)
    • 0.0.0.0 (all interfaces)
    • 127.0.0.1 (loopback)
    • localhost (if available)
    • Current machine IP address
  4. Fallback: If no port found in range, fall back to random port selection
  5. Error Handling: Handle network-specific errors (EADDRNOTAVAIL, ENOTFOUND, etc.)

Error Handling

/**
 * Thrown when the specified IP address is not available on this machine
 */
class IPAddressNotAvailableError extends Error {
  constructor(options?: ErrorOptions);
}

Usage Example:

import { detectPort, IPAddressNotAvailableError } from "detect-port";

try {
  const port = await detectPort({
    port: 3000,
    hostname: "192.168.1.999" // Invalid IP
  });
} catch (error) {
  if (error instanceof IPAddressNotAvailableError) {
    console.error("The specified IP address is not available on this machine");
  } else {
    console.error("Other error:", error);
  }
}