CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-portfinder

A simple tool to find an open port on the current machine

82

1.64x
Overview
Eval results
Files

port-finding.mddocs/

Port Finding

Core port discovery functionality for finding single or multiple available ports with configurable host and range options.

Capabilities

Get Port Function

Finds and returns an unbound port on the current machine. Supports both callback and Promise-based usage.

/**
 * Responds with a unbound port on the current machine
 * @param {PortFinderOptions} [options] - Port search options
 * @param {function} [callback] - Callback function (err, port) => void
 * @returns {Promise<number>} Promise resolving to available port (when no callback provided)
 */
function getPort(options?: PortFinderOptions): Promise<number>;
function getPort(callback: (err: Error, port: number) => void): void;
function getPort(options: PortFinderOptions, callback: (err: Error, port: number) => void): void;

Usage Examples:

const portfinder = require('portfinder');

// Basic usage with callback
portfinder.getPort(function (err, port) {
  if (err) throw err;
  console.log('Available port:', port); // e.g., 8000
});

// Promise-based usage
portfinder.getPortPromise()
  .then((port) => {
    console.log('Available port:', port);
  })
  .catch((err) => {
    console.error('Error finding port:', err);
  });

// With options - callback style
portfinder.getPort({
  port: 3000,
  stopPort: 3010,
  host: 'localhost'
}, function(err, port) {
  if (err) throw err;
  console.log('Port found:', port); // between 3000-3010 on localhost
});

// With options - Promise style
portfinder.getPort({
  port: 8080,
  host: '127.0.0.1'
})
.then(port => {
  console.log('Port on 127.0.0.1:', port);
});

Get Port Promise Function

Promise-based version of getPort (alias for getPort without callback).

/**
 * Responds a promise of an unbound port on the current machine
 * @param {PortFinderOptions} [options] - Port search options  
 * @returns {Promise<number>} Promise resolving to available port
 */
function getPortPromise(options?: PortFinderOptions): Promise<number>;

Usage Example:

const portfinder = require('portfinder');

// Equivalent to getPort without callback
const port = await portfinder.getPortPromise({
  port: 4000,
  stopPort: 5000
});
console.log('Found port:', port);

Get Ports Function

Finds and returns an array of unbound ports on the current machine.

/**
 * Responds with an array of unbound ports on the current machine
 * @param {number} count - The number of ports to find
 * @param {PortFinderOptions} [options] - Port search options
 * @param {function} [callback] - Callback function (err, ports) => void
 * @returns {Promise<number[]>} Promise resolving to array of available ports (when no callback provided)
 */
function getPorts(count: number, options?: PortFinderOptions): Promise<number[]>;
function getPorts(count: number, callback: (err: Error, ports: number[]) => void): void;
function getPorts(count: number, options: PortFinderOptions, callback: (err: Error, ports: number[]) => void): void;

Usage Examples:

const portfinder = require('portfinder');

// Find 3 consecutive ports - callback style
portfinder.getPorts(3, function(err, ports) {
  if (err) throw err;
  console.log('Available ports:', ports); // e.g., [8000, 8001, 8002]
});

// Find 5 ports with options - Promise style
portfinder.getPorts(5, {
  port: 9000,
  stopPort: 9100
})
.then(ports => {
  console.log('5 ports found:', ports); // e.g., [9000, 9001, 9002, 9003, 9004]  
});

// Find 2 ports on specific host
portfinder.getPorts(2, {
  host: '0.0.0.0',
  port: 3000
}, function(err, ports) {
  console.log('Ports on all interfaces:', ports);
});

Get Ports Promise Function

Promise-based version of getPorts (alias for getPorts without callback).

/**
 * Responds a promise that resolves to an array of unbound ports on the current machine
 * @param {number} count - The number of ports to find
 * @param {PortFinderOptions} [options] - Port search options
 * @returns {Promise<number[]>} Promise resolving to array of available ports
 */
function getPortsPromise(count: number, options?: PortFinderOptions): Promise<number[]>;

Usage Example:

const portfinder = require('portfinder');

// Equivalent to getPorts without callback
const ports = await portfinder.getPortsPromise(4, {
  port: 7000,
  host: 'localhost'
});
console.log('Found ports:', ports);

Next Port Function

Gets the next port in sequence from the specified port (simply port + 1).

/**
 * Gets the next port in sequence from the specified port
 * @param {number} port - Port to increment from
 * @returns {number} Next port (port + 1)
 */
function nextPort(port: number): number;

Usage Example:

const portfinder = require('portfinder');

const currentPort = 8000;
const nextPort = portfinder.nextPort(currentPort);
console.log('Next port:', nextPort); // 8001

// Useful for manual port iteration
let testPort = 3000;
while (testPort < 3010) {
  // Test port availability logic here
  testPort = portfinder.nextPort(testPort);
}

Options Interface

/**
 * Options for port finding operations
 */
interface PortFinderOptions {
  /**
   * Host to find available port on
   * If not specified, tests all available network interfaces
   */
  host?: string;
  
  /**
   * Minimum port (takes precedence over global basePort)
   * Port search will start from this value
   */
  port?: number;
  
  /**
   * Search start port (equals port when not provided)
   * This exists because getPort mutates port state in recursive calls
   * and doesn't have a way to retrieve beginning port while searching
   */
  startPort?: number;
  
  /**
   * Maximum port (takes precedence over global highestPort)
   * Port search will not exceed this value
   */
  stopPort?: number;
}

Advanced Usage Patterns

Testing Multiple Hosts

const portfinder = require('portfinder');

const hosts = ['127.0.0.1', '0.0.0.0', 'localhost'];
const promises = hosts.map(host => 
  portfinder.getPortPromise({ port: 8000, host })
    .then(port => ({ host, port }))
    .catch(err => ({ host, error: err.message }))
);

Promise.all(promises).then(results => {
  console.log('Port availability by host:', results);
});

Port Range Allocation

const portfinder = require('portfinder');

// Allocate ports for microservices
async function allocateServicePorts() {
  const services = ['api', 'auth', 'cache', 'db'];
  const basePorts = [8000, 8100, 8200, 8300];
  
  const allocations = await Promise.all(
    services.map(async (service, index) => {
      const port = await portfinder.getPortPromise({
        port: basePorts[index],
        stopPort: basePorts[index] + 50
      });
      return { service, port };
    })
  );
  
  return allocations;
}

allocateServicePorts().then(allocations => {
  console.log('Service port allocations:', allocations);
  // e.g., [
  //   { service: 'api', port: 8000 },
  //   { service: 'auth', port: 8100 },
  //   { service: 'cache', port: 8201 },
  //   { service: 'db', port: 8300 }
  // ]
});

Error Recovery

const portfinder = require('portfinder');

async function findPortWithFallback(preferredPort) {
  try {
    // Try preferred port first
    return await portfinder.getPortPromise({
      port: preferredPort,
      stopPort: preferredPort
    });
  } catch (err) {
    console.log(`Port ${preferredPort} not available, finding alternative...`);
    
    // Fall back to range search
    return await portfinder.getPortPromise({
      port: preferredPort,
      stopPort: preferredPort + 100
    });
  }
}

findPortWithFallback(3000).then(port => {
  console.log('Using port:', port);
});

Install with Tessl CLI

npx tessl i tessl/npm-portfinder

docs

index.md

port-configuration.md

port-finding.md

socket-finding.md

tile.json