get-port

repository·main·Indexed 21 days ago

https://github.com/sindresorhus/get-port

A utility to find an available TCP port on a machine. It supports preferred ports, port ranges via portNumbers(), and port reservation to prevent in-process race conditions. Version 7.2.0 provides functions like getPort() and clearLockedPorts() to manage port availability and internal locking mechanisms.

Tokens
1.8K
Snippets
8
Records
9
Agent score
26%

What's inside get-port

  1. Avoid race conditions when using get-port

    main

    There are two types of race conditions to be aware of:

    In-process race conditions

    To prevent multiple calls within the same process (e.g., parallel Jest tests) from receiving the same port, get-port uses a lightweight locking mechanism. Returned ports are held for 15-30 seconds before they can be reused.

    Solution: If your delay between calling getPort() and binding to the port exceeds 30 seconds (common in long-running test suites), use the {reserve: true} option to lock the port for the entire lifetime of the process.

    Multi-process race conditions

    There is a very small chance another external process might claim a port between the time you request it and the time you bind to it. This will result in an EADDRINUSE error, which your application should handle by retrying.

  2. Clear locked ports with clearLockedPorts()

    main

    The clearLockedPorts() function clears the internal cache of locked ports, including any ports locked using the reserve: true option. This allows subsequent calls to getPort() to potentially return ports that were previously returned and held by the internal locking mechanism.

    Warning: Clearing the cache removes protection against in-process race conditions.

    import getPort, {clearLockedPorts} from 'get-port';
    
    const port = [3000, 3001, 3002];
    
    console.log(await getPort({port}));
    //=> 3000
    
    console.log(await getPort({port}));
    //=> 3001
    
    // Clear the cache to reset the selection state
    clearLockedPorts();
    
    console.log(await getPort({port}));
    //=> 3000
  3. Get an available TCP port with getPort()

    main

    The getPort() function returns a Promise that resolves to an available TCP port number. By default, it checks availability on all local addresses defined in the OS network interfaces.

    import getPort from 'get-port';
    
    console.log(await getPort());
    //=> 51402
  4. Configure getPort() options

    main

    You can pass an options object to getPort() to customize the port selection process.

    Options Reference

    OptionTypeDescription
    portnumber | Iterable<number>A preferred port or an iterable of preferred ports to use. If none are available, it falls back to a random port.
    excludeIterable<number>Ports that should not be returned. You can pass the result of portNumbers() here.
    reserveboolean(Default: false) If true, the port is locked for the lifetime of the process instead of the default 15-30 seconds. Useful for long-running test suites.
    hoststringThe host (IPv4 or IPv6) on which port resolution should be performed. If set, it only checks the given host.
    import getPort from 'get-port';
    
    // Use a single preferred port
    console.log(await getPort({port: 3000}));
    
    // Use an array of preferred ports
    console.log(await getPort({port: [3000, 3001, 3002]}));
  5. Generate a range of ports with portNumbers()

    main

    The portNumbers(from, to) helper generates an Iterable of port numbers within a specific range. This is useful for providing a range of preferred ports to getPort() or for populating the exclude option.

    Parameters

    • from: The first port of the range. Must be in the range 1024...65535.
    • to: The last port of the range. Must be in the range 1024...65535 and must be greater than from.
    import getPort, {portNumbers} from 'get-port';
    
    console.log(await getPort({port: portNumbers(3000, 3100)}));
    // Will use any port from 3000 to 3100, otherwise fall back to a random port
  6. Clear all locked and reserved ports with `clearLockedPorts()`

    main

    The clearLockedPorts() function clears all internal tracking of ports that were previously marked as locked (both old and young sets) or reserved. Use this if you need to reset the state of the port availability tracker within your process.

    import { clearLockedPorts } from 'get-port';
    
    clearLockedPorts();
  7. Get an available port with `getPorts()`

    main

    The default export getPorts is an asynchronous function used to find an available network port. It can accept an options object to specify a preferred port, exclude specific ports, or reserve the found port to prevent in-process races.

    Options

    • port: A number or an array of numbers representing the preferred port(s) to check. If 0 is provided, it will attempt to find any available port.
    • exclude: An iterable of numbers representing ports that should be skipped.
    • reserve: A boolean. If true, the found port is added to a process-wide reservedPorts set to avoid in-process races. If false (default), the port is added to a temporary lockedPorts set that is cleared periodically.
    • host: A specific host address to bind to (e.g., '127.0.0.1').

    If no ports in the provided sequence are available, the function throws an error: No available ports found.

    import getPorts from 'get-port';
    
    // Get any available port
    const port = await getPorts();
    
    // Get a specific port, or the next available one if that is taken
    const port = await getPorts({ port: 3000 });
    
    // Get a port while excluding specific ones
    const port = await getPorts({ port: 3000, exclude: [3001, 3002] });
    
    // Reserve a port to avoid in-process races
    const port = await getPorts({ port: 3000, reserve: true });
  8. Generate a range of port numbers with `portNumbers()`

    main

    The portNumbers(from, to) function returns a generator that yields integers from from to to inclusive. This is useful for providing a range of ports to getPorts().

    Constraints

    • from and to must be integers.
    • Both must be between 1024 and 65535.
    • from must be less than or equal to to.

    Throws TypeError for non-integers and RangeError for values outside the valid range or if from > to.

    import { portNumbers } from 'get-port';
    
    const ports = portNumbers(3000, 3005);
    
    for (const port of ports) {
    	console.log(port);
    }