process.ts

Declarations
#

27 declarations

view source

attach_process_error_handler
#

process.ts view source

(options?: { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more ... | undefined; } | undefined): () => void

Attaches an uncaughtException handler to the default registry.

options?

type { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more...
optional

returns

() => void

see also

  • ``ProcessRegistry.attach_error_handler``

despawn
#

process.ts view source

(child: ChildProcess, options?: DespawnOptions | undefined): Promise<SpawnResult>

Kills a child process and returns the result.

child

type ChildProcess

options?

type DespawnOptions | undefined
optional

returns

Promise<SpawnResult>

examples

const result = await despawn(child, {timeout_ms: 5000}); // If process ignores SIGTERM, SIGKILL sent after 5s

despawn_all
#

process.ts view source

(options?: DespawnOptions | undefined): Promise<SpawnResult[]>

Kills all processes in the default registry.

options?

type DespawnOptions | undefined
optional

returns

Promise<SpawnResult[]>

DespawnOptions
#

process.ts view source

DespawnOptions

Options for killing processes.

signal

Signal to send.

type NodeJS.Signals

timeout_ms

Timeout in ms before escalating to SIGKILL. Must be non-negative. Useful for processes that may ignore SIGTERM. A value of 0 triggers immediate SIGKILL escalation.

type number

print_child_process
#

print_spawn_result
#

process_is_pid_running
#

process.ts view source

(pid: number): boolean

Checks if a process with the given PID is running. Uses signal 0 which checks existence without sending a signal.

pid

the process ID to check (must be a positive integer)

type number

returns

boolean

true if the process exists (even without permission to signal it), false if the process doesn't exist or if pid is invalid (non-positive, non-integer, NaN, Infinity)

process_registry_default
#

process.ts view source

ProcessRegistry

Default process registry used by module-level spawn functions. For testing or isolated process groups, create a new ProcessRegistry instance.

ProcessRegistry
#

process.ts view source

Manages a collection of spawned processes for lifecycle tracking and cleanup.

The default instance process_registry_default is used by module-level functions. Create separate instances for isolated process groups or testing.

examples

// Use default registry via module functions const result = await spawn('echo', ['hello']); // Or create isolated registry for testing const registry = new ProcessRegistry(); const {child, closed} = registry.spawn('node', ['server.js']); await registry.despawn_all();

processes

All currently tracked child processes

type Set<ChildProcess>

readonly

spawn

Spawns a process and tracks it in this registry. The process is automatically unregistered when it exits.

type (command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): SpawnedProcess

command

the command to run

type string
args

arguments to pass to the command

type readonly string[]
default []
options?

spawn options including signal and timeout_ms

type SpawnProcessOptions | undefined
optional

handle with child process and closed promise

spawn_out

Spawns a process and captures stdout/stderr as strings. Sets stdio: 'pipe' automatically.

type (command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnedOut>

command

the command to run

type string
args

arguments to pass to the command

type readonly string[]
default []
options?

spawn options

type SpawnProcessOptions | undefined
optional
returns Promise<SpawnedOut>

result with captured stdout and stderr - null means spawn failed (ENOENT, etc.) or stream was unavailable - '' (empty string) means process ran but produced no output - non-empty string contains the captured output

despawn

Kills a child process and waits for it to exit.

type (child: ChildProcess, options?: DespawnOptions | undefined): Promise<SpawnResult>

child

the child process to kill

type ChildProcess
options?

kill options including signal and timeout

type DespawnOptions | undefined
optional
returns Promise<SpawnResult>

the spawn result after the process exits

despawn_all

Kills all processes in this registry.

type (options?: DespawnOptions | undefined): Promise<SpawnResult[]>

options?

kill options applied to all processes

type DespawnOptions | undefined
optional
returns Promise<SpawnResult[]>

array of spawn results

attach_error_handler

Attaches an uncaughtException handler that kills all processes before exiting. Prevents zombie processes when the parent crashes.

By default uses SIGKILL for immediate termination. Set graceful_timeout_ms to attempt SIGTERM first (allowing processes to clean up) before escalating to SIGKILL after the timeout.

Note: Node's uncaughtException handler cannot await async operations, so graceful shutdown uses a blocking busy-wait. This may not be sufficient for processes that need significant cleanup time.

type (options?: { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more ... | undefined; } | undefined): () => void

options?

configuration options

type { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more...
optional
returns () => void

cleanup function to remove the handler

RestartableProcess
#

process.ts view source

RestartableProcess

Handle for a process that can be restarted. Exposes closed promise for observing exits and implementing restart policies.

restart

Restart the process, killing the current one if active. Concurrent calls are coalesced - multiple calls before the first completes will share the same restart operation.

type () => Promise<void>

kill

Kill the process and set active to false

type () => Promise<void>

active

Whether this handle is managing a process.

Note: This reflects handle state, not whether the underlying OS process is executing. Remains true after a process exits naturally until kill() or restart() is called. To check if the process actually exited, await closed.

type boolean
readonly

child

The current child process, or null if not active

type ChildProcess | null
readonly

closed

Promise that resolves when the current process exits

type Promise<SpawnResult>
readonly

spawned

Promise that resolves when the initial spawn_process() call completes.

Note: This resolves when the spawn syscall returns, NOT when the process is "ready" or has produced output. For commands that fail immediately (e.g., ENOENT), spawned still resolves - check closed for errors.

type Promise<void>
readonly

spawn
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnResult>

Spawns a process and returns a promise that resolves when it exits. Use this for commands that complete (not long-running processes).

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

Promise<SpawnResult>

examples

const result = await spawn('npm', ['install']); if (!result.ok) console.error('Install failed');

spawn_detached
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnOptions | undefined): SpawnDetachedResult

Spawns a detached process that continues after parent exits.

Unlike other spawn functions, this is NOT tracked in any ProcessRegistry. The spawned process is meant to outlive the parent (e.g., daemon processes).

command

the command to run

type string

args

arguments to pass to the command

type readonly string[]
default []

options?

spawn options (use stdio to redirect output to file descriptors)

type SpawnOptions | undefined
optional

returns

SpawnDetachedResult

result with pid on success, or error message on failure

examples

// Simple detached process const result = spawn_detached('node', ['daemon.js'], {cwd: '/app'}); // With log file (caller handles file opening) import {openSync, closeSync} from 'node:fs'; const log_fd = openSync('/var/log/daemon.log', 'a'); const result = spawn_detached('node', ['daemon.js'], { cwd: '/app', stdio: ['ignore', log_fd, log_fd], }); closeSync(log_fd);

spawn_out
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnedOut>

Spawns a process and captures stdout/stderr as strings.

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

Promise<SpawnedOut>

examples

const {result, stdout} = await spawn_out('git', ['status', '--porcelain']); if (result.ok && stdout) console.log(stdout);

spawn_process
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): SpawnedProcess

Spawns a process with graceful shutdown behavior. Returns a handle with access to the child process and closed promise.

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

SpawnedProcess

examples

const {child, closed} = spawn_process('node', ['server.js']); // Later... child.kill(); const result = await closed;

spawn_restartable_process
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): RestartableProcess

Spawns a process that can be restarted. Handles concurrent restart calls gracefully.

Note: The signal and timeout_ms options are reapplied on each restart. If the AbortSignal is already aborted when restart() is called, the new process will be killed immediately.

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

RestartableProcess

examples

Simple restart on crash

const rp = spawn_restartable_process('node', ['server.js']); while (rp.active) { const result = await rp.closed; if (result.ok) break; // Clean exit await rp.restart(); }

Restart with backoff

const rp = spawn_restartable_process('node', ['server.js']); let failures = 0; while (rp.active) { const result = await rp.closed; if (result.ok || ++failures > 5) break; await new Promise((r) => setTimeout(r, 1000 * failures)); await rp.restart(); }

spawn_result_is_error
#

process.ts view source

(result: SpawnResult): result is SpawnResultError

Type guard for spawn errors (process failed to start).

result

returns

boolean

spawn_result_is_exited
#

spawn_result_is_signaled
#

spawn_result_to_message
#

SpawnDetachedResult
#

SpawnedOut
#

process.ts view source

SpawnedOut

Result of spawn_out with captured output streams.

result

stdout

Captured stdout, or null if stream unavailable

type string | null

stderr

Captured stderr, or null if stream unavailable

type string | null

SpawnedProcess
#

process.ts view source

SpawnedProcess

Handle for a spawned process with access to the child and completion promise.

child

The underlying Node.js ChildProcess

type ChildProcess

closed

Resolves when the process exits

type Promise<SpawnResult>

SpawnProcessOptions
#

process.ts view source

SpawnProcessOptions

Options for spawning processes, extending Node's SpawnOptions.

inheritance

extends:
  • SpawnOptions

signal

AbortSignal to cancel the process. When aborted, sends SIGTERM to the child.

type AbortSignal

timeout_ms

Timeout in milliseconds. Must be non-negative. Sends SIGTERM when exceeded. A value of 0 triggers immediate SIGTERM.

type number

spawn_child_process

Custom spawn function for testing. Defaults to node:child_process spawn.

type typeof node_spawn_child_process

SpawnResult
#

SpawnResultError
#

process.ts view source

SpawnResultError

Spawn failed before the process could run.

examples

ENOENT when command not found

ok

type false

child

type ChildProcess

error

type Error

code

type null

signal

type null

SpawnResultExited
#

process.ts view source

SpawnResultExited

Process ran and exited with a code. ok is true when code is 0.

ok

type boolean

child

type ChildProcess

error

type null

code

type number

signal

type null

SpawnResultSignaled
#

process.ts view source

SpawnResultSignaled

Process was terminated by a signal (e.g., SIGTERM, SIGKILL).

ok

type false

child

type ChildProcess

error

type null

code

type null

signal

type NodeJS.Signals

Depends on
#

Imported by
#