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
postgresBinary 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
listenListen configuration used to connect to Postgres.databaseDatabase to create when missing.bootstrapDatabaseExisting database used for the creation connection. Defaults topostgres.userOptional user for the creation connection.passwordOptional 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
dataDirActual Postgres cluster directory. This is the directory that containsPG_VERSION, not necessarily the caller's outer workspace directory.binariesPre-resolved binaries to reuse instead of resolving again.postgresBinary resolution behavior whenbinariesis omitted.encodingEncoding passed toinitdb -E.localeLocale passed toinitdb --locale, orfalseto pass--no-locale.usernameBootstrap database superuser name. Defaults to the current OS user.authAuthentication method passed toinitdb --auth.noSyncPass--nosynctoinitdbfor faster, less durable initialization.configSettings appended topostgresql.confafter a new cluster is initialized.initdbOutputDestination for rawinitdbstdout and stderr.loggerOptional lifecycle logger. Missing methods are treated as no-ops.
š InitPostgresDataDirOptions on GitHub
InitPostgresDataDirResult
Result of initPostgresDataDir.
export interface InitPostgresDataDirResult {
dataDir: string;
version?: string;
}
Properties
dataDirInitialized or existing data directory.versionResolved 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
infoCalled for normal lifecycle progress messages.warnCalled when a recoverable fallback or unusual condition occurs.errorCalled 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
dataDirData directory passed tostartPostgresDataDir.listenNormalized listen configuration used by the server.portPort used by the server.hostTCP host when the server is listening on TCP.socketDirSocket directory when the server is listening on a Unix socket.pidChild process id reported by Node.js when available.stopStops the server process. Safe to call more than once.[Symbol.asyncDispose]Supportsawait usingby delegating tostop().
š LocalPostgresProcess on GitHub
PostgresBinaryOptions
Options that control which postgres and initdb binaries are used.
export interface PostgresBinaryOptions {
version?: string;
strategy?: PostgresBinaryStrategy;
cacheDir?: string;
}
Properties
versionRequired Postgres version. A major version such as18accepts any matching major version. More specific values require matching components.strategyHow local binaries and managed downloads should be resolved.Defaults to
prefer-localwhen this object is provided. Whenpostgresis omitted,local-onlypreserves the package's original behavior.cacheDirDirectory 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
typeStart a TCP listener.typeStart 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
filePathFile 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
initdbPath or command name for theinitdbexecutable.postgresPath or command name for thepostgresexecutable.sourceWhether the binaries came from PATH or a managed package download.versionParsed 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
typeTCP listener.typeUnix 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
dataDirActual Postgres cluster directory to start.binariesPre-resolved binaries to reuse instead of resolving again.listenListen configuration. Defaults to TCP on an available local port.postgresBinary resolution behavior whenbinariesis omitted.postgresOptionsAdditional command-line arguments passed to thepostgresprocess.postgresOutputDestination for rawpostgresserver stdout and stderr.loggerOptional lifecycle logger. Missing methods are treated as no-ops.readinessTimeoutMsMaximum time to wait for Postgres to accept client connections.readinessIntervalMsDelay between readiness checks.stopTimeoutMsMaximum 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
dataDirActual Postgres cluster directory that containspostmaster.pid.expectedPidStop only whenpostmaster.pidstill identifies this process. This keeps delayed cleanup jobs from stopping a newer server that reused the directory.listenListen configuration used when waiting for idle connections.modePostgreSQL shutdown mode. Defaults tofast.waitForIdleWait for client connections to fall below a threshold before signaling.timeoutMsMaximum time to wait after signaling Postgres to stop.loggerOptional lifecycle logger. Missing methods are treated as no-ops.databaseDatabase 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
listenListen configuration to connect through.databaseDatabase used for readiness probes. Defaults topostgres.userOptional user for readiness probes.passwordOptional password for readiness probes.timeoutMsMaximum time to wait for readiness.intervalMsDelay between readiness checks.