Node.js implementation of port detector that finds available network ports automatically
npx @tessl/cli install tessl/npm-detect-port@2.1.0Detect Port is a Node.js library that automatically finds available network ports when specified ports are occupied. It provides both programmatic APIs with full TypeScript support and command-line interfaces for detecting open ports, with the core functionality being the ability to suggest alternative ports when the requested port is unavailable.
npm install detect-portimport { detect, detectPort, waitPort } from "detect-port";For CommonJS:
const { detect, detectPort, waitPort } = require("detect-port");Default import (same as detectPort):
import detect from "detect-port";import { detect } from "detect-port";
// Check if port 3000 is available
const availablePort = await detect(3000);
if (availablePort === 3000) {
console.log("Port 3000 is available");
} else {
console.log(`Port 3000 is occupied, suggested port: ${availablePort}`);
}
// Get a random available port
const randomPort = await detect();
console.log(`Random available port: ${randomPort}`);Detect Port is built around several key components:
Core port detection functionality that finds available ports by trying the specified port and incrementing if occupied.
function detectPort(port?: number | PortConfig | string): Promise<number>;
function detectPort(callback: DetectPortCallback): void;
function detectPort(port: number | PortConfig | string | undefined, callback: DetectPortCallback): void;
// Alias for detectPort
const detect: typeof detectPort;
interface PortConfig {
port?: number | string;
hostname?: string | undefined;
callback?: DetectPortCallback;
}
type DetectPortCallback = (err: Error | null, port?: number) => void;Utility for waiting until a specified port becomes available (occupied by another process).
function waitPort(port: number, options?: WaitPortOptions): Promise<boolean>;
interface WaitPortOptions {
retryInterval?: number;
retries?: number;
}class IPAddressNotAvailableError extends Error {
constructor(options?: ErrorOptions);
}
class WaitPortRetryError extends Error {
retries: number;
count: number;
constructor(message: string, retries: number, count: number, options?: ErrorOptions);
}The package includes command-line tools for port detection (available as both detect and detect-port commands):
# Get a random available port
detect
# or
detect-port
# Check a specific port
detect 3000
detect-port 3000
# Verbose output
detect 3000 --verbose
# Show version
detect --version
detect -v
# Show help
detect --help
detect -h