Port waiting functionality allows you to wait until a specified port becomes available (i.e., occupied by another process). This is useful for scenarios where you need to wait for a server to start up or become ready.
Waits for a port to become available by repeatedly checking if the port is occupied.
/**
* Waits for a port to become available (occupied by another process)
* @param port - Port number to wait for
* @param options - Configuration options for retry behavior
* @returns Promise that resolves to true when port becomes available, or throws on timeout
*/
function waitPort(port: number, options?: WaitPortOptions): Promise<boolean>;
/**
* Options for configuring port waiting behavior
*/
interface WaitPortOptions {
/** Interval between retry attempts in milliseconds (default: 1000) */
retryInterval?: number;
/** Maximum number of retry attempts (default: Infinity) */
retries?: number;
}Usage Examples:
import { waitPort } from "detect-port";
// Wait for port 3000 to become available (default options)
try {
await waitPort(3000);
console.log("Port 3000 is now available!");
} catch (error) {
console.error("Failed to wait for port:", error);
}
// Wait with custom retry options
try {
await waitPort(8080, {
retryInterval: 500, // Check every 500ms
retries: 20 // Give up after 20 attempts (10 seconds)
});
console.log("Port 8080 is now available!");
} catch (error) {
console.error("Timeout waiting for port 8080");
}
// Wait indefinitely with custom interval
await waitPort(9000, {
retryInterval: 2000 // Check every 2 seconds, retry forever
});Waiting for Server Startup:
import { waitPort } from "detect-port";
import { spawn } from "child_process";
// Start a server process
const serverProcess = spawn("node", ["server.js"]);
// Wait for the server to be ready
try {
await waitPort(3000, { retries: 30, retryInterval: 1000 });
console.log("Server is ready!");
// Now safe to make requests to the server
// ... your application logic
} catch (error) {
console.error("Server failed to start within 30 seconds");
serverProcess.kill();
}Integration Testing:
import { waitPort } from "detect-port";
async function setupTestEnvironment() {
// Start test database
const dbProcess = startTestDatabase();
// Wait for database to be ready
await waitPort(5432, { retries: 20, retryInterval: 500 });
// Start application server
const appProcess = startTestServer();
// Wait for application to be ready
await waitPort(3000, { retries: 15, retryInterval: 1000 });
console.log("Test environment is ready!");
return { dbProcess, appProcess };
}/**
* Error thrown when waitPort exceeds the maximum number of retry attempts
*/
class WaitPortRetryError extends Error {
/** Maximum number of retries that were configured */
retries: number;
/** Actual number of attempts made (including the first attempt) */
count: number;
constructor(message: string, retries: number, count: number, options?: ErrorOptions);
}Usage Example:
import { waitPort, WaitPortRetryError } from "detect-port";
try {
await waitPort(3000, { retries: 5, retryInterval: 1000 });
} catch (error) {
if (error instanceof WaitPortRetryError) {
console.error(`Failed to detect port availability after ${error.count} attempts`);
console.error(`Maximum retries configured: ${error.retries}`);
} else {
console.error("Unexpected error:", error);
}
}The waitPort function operates by:
detectPort function to check if the specified port is availabledetectPort returns the same port number, it means the port is free (not what we want)detectPort returns a different port number, indicating the original port is now occupiedretryInterval before trying againretries, it throws a WaitPortRetryErrorNote: This function waits for a port to become occupied (busy), not free. This is useful for waiting for servers to start up and begin listening on their designated ports.