Skip to main content

Class Overview

Manages route mappings stored as a JSON file on disk. Provides file locking for concurrent access, automatic cleanup of stale routes, and process lifecycle tracking.

Constructor

string
required
Path to the state directory where route data will be stored. The directory will be created if it doesn’t exist.
object
Optional configuration

Properties

string
The state directory path (read-only)
string
Path to the proxy PID file (read-only)
string
Path to the proxy port file (read-only)

Methods

ensureDir()

Creates the state directory if it doesn’t exist and sets appropriate permissions. Automatically called by addRoute() and removeRoute(). Example:

addRoute()

Registers a route mapping from a hostname to a local port. Acquires a file lock, checks for conflicts, and persists the route to disk.
string
required
The hostname to register (e.g., “api.localhost”)
number
required
The local port the application is listening on
number
required
Process ID of the owning process. Use process.pid for the current process, or 0 for system-managed routes.
boolean
default:"false"
Override an existing route even if owned by a live process
Throws:
  • RouteConflictError - When hostname is already registered by a live process and force is false
  • Error - When the file lock cannot be acquired
Example:

removeRoute()

Unregisters a route mapping. Acquires a file lock and removes the route from persistent storage.
string
required
The hostname to unregister
Throws:
  • Error - When the file lock cannot be acquired
Example:

loadRoutes()

Loads all routes from disk, filtering out stale entries whose owning process is no longer alive.
boolean
default:"false"
When true, writes the cleaned-up route list back to disk. Only safe when the caller already holds the lock (used internally by addRoute and removeRoute).
Returns:
  • RouteMapping[] - Array of live route mappings
Example:

getRoutesPath()

Returns the absolute path to the routes JSON file. Example:

File Locking

The RouteStore uses directory-based file locking to coordinate concurrent access:
  • Lock acquisition retries up to 20 times with 50ms delays
  • Stale locks (older than 10 seconds) are automatically removed
  • All write operations (addRoute, removeRoute) acquire the lock automatically
Do not manually modify the routes file while applications are running. Use the RouteStore API to ensure proper locking.

Stale Route Cleanup

Routes are automatically cleaned up when:
  1. The owning process terminates (detected via PID check)
  2. Any method loads the routes from disk
  3. Routes with pid: 0 are never removed (system-managed)

Error Handling

RouteConflictError

Thrown when attempting to register a hostname that’s already in use:

Complete Example

Type Definitions

Constants

createProxyServer

Create a proxy server that uses routes

Type Definitions

Complete type reference