Reference

local-postgres/core

Functions

ensurePostgresDatabase

Creates a database when it does not already exist.

The database name is safely quoted before execution. The connection is made through bootstrapDatabase, or postgres when that option is omitted.

export function ensurePostgresDatabase(options: EnsurePostgresDatabaseOptions): Promise<void>;

šŸ” ensurePostgresDatabase on GitHub

getPostgresVersion

Resolves a Postgres binary and returns its parsed version.

Use this before initializing a data directory when the caller needs the binary version to choose a versioned cluster path.

export function getPostgresVersion(options?: {
  postgres?: PostgresBinaryOptions;
}): Promise<string>;

Properties

  • postgres Binary resolution behavior.

šŸ” getPostgresVersion on GitHub

initPostgresDataDir

Creates and initializes a Postgres data directory when needed.

If PG_VERSION already exists, this validates the data directory against the resolved binary major version when known and leaves existing configuration untouched.

export function initPostgresDataDir(options: InitPostgresDataDirOptions): Promise<InitPostgresDataDirResult>;

šŸ” initPostgresDataDir on GitHub

resolvePostgresBinaries

Resolves the postgres and initdb binaries that lifecycle helpers would use.

By default, this checks local binaries from PATH. Provide options to require a version or opt into managed package downloads.

export function resolvePostgresBinaries(options?: PostgresBinaryOptions): Promise<ResolvedPostgresBinaries>;

šŸ” resolvePostgresBinaries on GitHub

startPostgresDataDir

Starts a Postgres server for an existing data directory.

The returned process resolves only after Postgres accepts client connections. Call stop() or use await using to shut the process down.

export function startPostgresDataDir(options: StartPostgresDataDirOptions): Promise<LocalPostgresProcess>;

šŸ” startPostgresDataDir on GitHub

stopPostgresDataDir

Stops a Postgres data directory by reading its postmaster.pid file.

This is useful for cleanup from a different process than the one that started Postgres. If no postmaster.pid exists, the function resolves without signaling anything.

export function stopPostgresDataDir(options: StopPostgresDataDirOptions): Promise<void>;

šŸ” stopPostgresDataDir on GitHub

waitForPostgresReady

Waits until Postgres accepts a client connection through the given listener.

export function waitForPostgresReady(options: WaitForPostgresReadyOptions): Promise<void>;

šŸ” waitForPostgresReady on GitHub

import { Writable } from "node:stream";

Classes

LocalPostgresError

Error type used for operational failures reported by local-postgres.

export class LocalPostgresError extends Error {
  /** Bounded Postgres process output captured while an operation was failing. */
  readonly diagnostics?: string;
  constructor(message: string, options?: ErrorOptions & {
    diagnostics?: string;
  });
}

šŸ” LocalPostgresError on GitHub

PostgresDataDirInUseError

Indicates that a data directory's postmaster.pid belongs to a live process.

export class PostgresDataDirInUseError extends LocalPostgresError {
  readonly dataDir: string;
  readonly pid: number;
  constructor(dataDir: string, pid: number);
}

šŸ” PostgresDataDirInUseError on GitHub

Constants

DEFAULT_POSTGRES_CACHE_DIR

Default directory used to cache managed Postgres binary packages.

export const DEFAULT_POSTGRES_CACHE_DIR: string;

šŸ” DEFAULT_POSTGRES_CACHE_DIR on GitHub

Types

EnsurePostgresDatabaseOptions

Options for creating a database when it does not already exist.

export interface EnsurePostgresDatabaseOptions {
  listen: PostgresListenOptions;
  database: string;
  bootstrapDatabase?: string;
  user?: string;
  password?: string;
}

Properties

  • listen Listen configuration used to connect to Postgres.

  • database Database to create when missing.

  • bootstrapDatabase Existing database used for the creation connection. Defaults to postgres.

  • user Optional user for the creation connection.

  • password Optional password for the creation connection.

šŸ” EnsurePostgresDatabaseOptions on GitHub

InitPostgresDataDirOptions

Options for initializing a Postgres data directory with initdb.

export interface InitPostgresDataDirOptions {
  dataDir: string;
  binaries?: ResolvedPostgresBinaries;
  postgres?: PostgresBinaryOptions;
  encoding?: string;
  locale?: string | false;
  username?: string;
  auth?: string;
  noSync?: boolean;
  config?: Record<string, PostgresConfigValue>;
  initdbOutput?: PostgresOutputTarget;
  logger?: Partial<LocalPostgresLogger>;
}

Properties

  • dataDir Actual Postgres cluster directory. This is the directory that contains PG_VERSION, not necessarily the caller's outer workspace directory.

  • binaries Pre-resolved binaries to reuse instead of resolving again.

  • postgres Binary resolution behavior when binaries is omitted.

  • encoding Encoding passed to initdb -E.

  • locale Locale passed to initdb --locale, or false to pass --no-locale.

  • username Bootstrap database superuser name. Defaults to the current OS user.

  • auth Authentication method passed to initdb --auth.

  • noSync Pass --nosync to initdb for faster, less durable initialization.

  • config Settings appended to postgresql.conf after a new cluster is initialized.

  • initdbOutput Destination for raw initdb stdout and stderr.

  • logger Optional lifecycle logger. Missing methods are treated as no-ops.

šŸ” InitPostgresDataDirOptions on GitHub

InitPostgresDataDirResult

Result of initPostgresDataDir.

export interface InitPostgresDataDirResult {
  dataDir: string;
  version?: string;
}

Properties

  • dataDir Initialized or existing data directory.

  • version Resolved binary version when known.

šŸ” InitPostgresDataDirResult on GitHub

LocalPostgresLogger

Receives lifecycle messages from local-postgres.

export interface LocalPostgresLogger {
  info(message: string): void;
  warn(message: string): void;
  error(message: string): void;
}

Properties

  • info Called for normal lifecycle progress messages.

  • warn Called when a recoverable fallback or unusual condition occurs.

  • error Called when the managed Postgres process exits unexpectedly.

šŸ” LocalPostgresLogger on GitHub

LocalPostgresProcess

Running Postgres process returned by the core lifecycle API.

export interface LocalPostgresProcess {
  dataDir: string;
  listen: ResolvedPostgresListenOptions;
  port: number;
  host?: string;
  socketDir?: string;
  pid?: number;
  stop(): Promise<void>;
  [Symbol.asyncDispose](): Promise<void>;
}

Properties

  • dataDir Data directory passed to startPostgresDataDir.

  • listen Normalized listen configuration used by the server.

  • port Port used by the server.

  • host TCP host when the server is listening on TCP.

  • socketDir Socket directory when the server is listening on a Unix socket.

  • pid Child process id reported by Node.js when available.

  • stop Stops the server process. Safe to call more than once.

  • [Symbol.asyncDispose] Supports await using by delegating to stop().

šŸ” LocalPostgresProcess on GitHub

PostgresBinaryOptions

Options that control which postgres and initdb binaries are used.

export interface PostgresBinaryOptions {
  version?: string;
  strategy?: PostgresBinaryStrategy;
  cacheDir?: string;
}

Properties

  • version Required Postgres version. A major version such as 18 accepts any matching major version. More specific values require matching components.

  • strategy How local binaries and managed downloads should be resolved.

    Defaults to prefer-local when this object is provided. When postgres is omitted, local-only preserves the package's original behavior.

  • cacheDir Directory for downloaded npm package tarballs and extracted binaries.

    Defaults to path.join(os.homedir(), ".local-postgres").

šŸ” PostgresBinaryOptions on GitHub

PostgresBinaryStrategy

Strategy for resolving local or managed Postgres binaries.

export type PostgresBinaryStrategy = 'local-only' | 'prefer-local' | 'prefer-download' | 'download-only';

šŸ” PostgresBinaryStrategy on GitHub

PostgresConfigValue

Value type accepted when appending PostgreSQL settings to postgresql.conf.

export type PostgresConfigValue = string | number | boolean;

šŸ” PostgresConfigValue on GitHub

PostgresListenOptions

Listen configuration for TCP or Unix socket Postgres servers.

export type PostgresListenOptions = {
  type: 'tcp'; /** TCP host passed to `postgres -h`. Defaults to `127.0.0.1`. */
  host?: string; /** TCP port. When omitted, an available local port is selected. */
  port?: number;
} | {
  type: 'socket'; /** Directory passed to `postgres -k` and used as the client host. */
  socketDir: string; /** Socket port component. Defaults to PostgreSQL's `5432`. */
  port?: number;
};

Properties

  • type Start a TCP listener.

  • type Start a Unix socket listener.

šŸ” PostgresListenOptions on GitHub

PostgresOutputTarget

Destination for Postgres process stdout and stderr. on-error keeps a bounded in-memory tail quiet during successful startup and adds it to a LocalPostgresError when startup fails.

export type PostgresOutputTarget = 'ignore' | 'inherit' | 'on-error' | {
  filePath: string;
} | Writable;

Properties

  • filePath File path that receives appended Postgres stdout and stderr output.

šŸ” PostgresOutputTarget on GitHub

ResolvedPostgresBinaries

Absolute or PATH-resolved binaries selected for lifecycle operations.

export interface ResolvedPostgresBinaries {
  initdb: string;
  postgres: string;
  source: 'local' | 'download';
  version?: string;
}

Properties

  • initdb Path or command name for the initdb executable.

  • postgres Path or command name for the postgres executable.

  • source Whether the binaries came from PATH or a managed package download.

  • version Parsed Postgres version when it could be inspected during resolution.

šŸ” ResolvedPostgresBinaries on GitHub

ResolvedPostgresListenOptions

Normalized listen configuration returned after defaults are applied.

export type ResolvedPostgresListenOptions = {
  type: 'tcp'; /** Concrete TCP host used by the server and clients. */
  host: string; /** Concrete TCP port used by the server and clients. */
  port: number;
} | {
  type: 'socket'; /** Concrete socket directory used by the server and clients. */
  socketDir: string; /** Concrete socket port component. */
  port: number;
};

Properties

  • type TCP listener.

  • type Unix socket listener.

šŸ” ResolvedPostgresListenOptions on GitHub

StartPostgresDataDirOptions

Options for starting an existing Postgres data directory.

export interface StartPostgresDataDirOptions {
  dataDir: string;
  binaries?: ResolvedPostgresBinaries;
  listen?: PostgresListenOptions;
  postgres?: PostgresBinaryOptions;
  postgresOptions?: string[];
  postgresOutput?: PostgresOutputTarget;
  logger?: Partial<LocalPostgresLogger>;
  readinessTimeoutMs?: number;
  readinessIntervalMs?: number;
  stopTimeoutMs?: number;
}

Properties

  • dataDir Actual Postgres cluster directory to start.

  • binaries Pre-resolved binaries to reuse instead of resolving again.

  • listen Listen configuration. Defaults to TCP on an available local port.

  • postgres Binary resolution behavior when binaries is omitted.

  • postgresOptions Additional command-line arguments passed to the postgres process.

  • postgresOutput Destination for raw postgres server stdout and stderr.

  • logger Optional lifecycle logger. Missing methods are treated as no-ops.

  • readinessTimeoutMs Maximum time to wait for Postgres to accept client connections.

  • readinessIntervalMs Delay between readiness checks.

  • stopTimeoutMs Maximum time to wait after each shutdown signal.

šŸ” StartPostgresDataDirOptions on GitHub

StopPostgresDataDirOptions

Options for stopping a Postgres data directory by reading postmaster.pid.

export interface StopPostgresDataDirOptions {
  dataDir: string;
  expectedPid?: number;
  listen?: PostgresListenOptions;
  mode?: 'smart' | 'fast' | 'immediate';
  waitForIdle?: boolean | {
    database?: string; /** Connection count threshold that is considered idle. Defaults to `0`. */
    minConnections?: number; /** Maximum time to wait for idle connections. */
    timeoutMs?: number; /** Delay between idle-connection checks. */
    intervalMs?: number;
  };
  timeoutMs?: number;
  logger?: Partial<LocalPostgresLogger>;
}

Properties

  • dataDir Actual Postgres cluster directory that contains postmaster.pid.

  • expectedPid Stop only when postmaster.pid still identifies this process. This keeps delayed cleanup jobs from stopping a newer server that reused the directory.

  • listen Listen configuration used when waiting for idle connections.

  • mode PostgreSQL shutdown mode. Defaults to fast.

  • waitForIdle Wait for client connections to fall below a threshold before signaling.

  • timeoutMs Maximum time to wait after signaling Postgres to stop.

  • logger Optional lifecycle logger. Missing methods are treated as no-ops.

  • database Database checked for active connections.

šŸ” StopPostgresDataDirOptions on GitHub

WaitForPostgresReadyOptions

Options for waiting until Postgres accepts client connections.

export interface WaitForPostgresReadyOptions {
  listen: PostgresListenOptions;
  database?: string;
  user?: string;
  password?: string;
  timeoutMs?: number;
  intervalMs?: number;
}

Properties

  • listen Listen configuration to connect through.

  • database Database used for readiness probes. Defaults to postgres.

  • user Optional user for readiness probes.

  • password Optional password for readiness probes.

  • timeoutMs Maximum time to wait for readiness.

  • intervalMs Delay between readiness checks.

šŸ” WaitForPostgresReadyOptions on GitHub