process.ts

view source

Declarations
#

24 declarations

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 import {attach_process_error_handler} from '@fuzdev/fuz_util/process.js';

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> import {despawn} from '@fuzdev/fuz_util/process.js';

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[]> import {despawn_all} from '@fuzdev/fuz_util/process.js';

Kills all processes in the default registry.

options?

type DespawnOptions | undefined
optional

returns

Promise<SpawnResult[]>

DespawnOptions
#

process.ts view source

DespawnOptions import type {DespawnOptions} from '@fuzdev/fuz_util/process.js';

Options for killing processes.

signal?

Signal to send.

type NodeJS.Signals

default 'SIGTERM'

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 import {process_is_pid_running} from '@fuzdev/fuz_util/process.js';

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 import {process_registry_default} from '@fuzdev/fuz_util/process.js';

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

import {ProcessRegistry} from '@fuzdev/fuz_util/process.js';

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

type string

args

type readonly string[]
default []

options?

spawn options including signal and timeout_ms

type SpawnProcessOptions | undefined
optional

throws

  • Error - if `timeout_ms` is negative

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

type string

args

type readonly string[]
default []

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

throws

  • Error - if `timeout_ms` is negative

despawn

Kills a child process and waits for it to exit.

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

child

type ChildProcess

options?

kill options including signal and timeout

type DespawnOptions | undefined
optional
returns Promise<SpawnResult>

throws

  • Error - if `timeout_ms` is negative

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[]>

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

throws

  • Error - if a handler is already attached to this registry

RestartableProcess
#

process.ts view source

RestartableProcess import type {RestartableProcess} from '@fuzdev/fuz_util/process.js';

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
const rp = spawn_restartable_process('node', ['server.js']); await rp.spawned; // Safe to access rp.child now

spawn
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnResult> import {spawn} from '@fuzdev/fuz_util/process.js';

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 import {spawn_detached} from '@fuzdev/fuz_util/process.js';

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

type string

args

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> import {spawn_out} from '@fuzdev/fuz_util/process.js';

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 import {spawn_process} from '@fuzdev/fuz_util/process.js';

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 import {spawn_restartable_process} from '@fuzdev/fuz_util/process.js';

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_to_message
#

process.ts view source

(result: SpawnResult): string import {spawn_result_to_message} from '@fuzdev/fuz_util/process.js';

Formats a spawn result for use in error messages.

result

returns

string

SpawnDetachedResult
#

process.ts view source

SpawnDetachedResult import type {SpawnDetachedResult} from '@fuzdev/fuz_util/process.js';

Result of spawning a detached process.

SpawnedOut
#

process.ts view source

SpawnedOut import type {SpawnedOut} from '@fuzdev/fuz_util/process.js';

Result of spawn_out with captured output streams.

result

type SpawnResult

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 import type {SpawnedProcess} from '@fuzdev/fuz_util/process.js';

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 import type {SpawnProcessOptions} from '@fuzdev/fuz_util/process.js';

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
#

process.ts view source

SpawnResult import type {SpawnResult} from '@fuzdev/fuz_util/process.js';

Discriminated union representing all possible spawn outcomes. Narrow via result.kind === 'error' | 'exited' | 'signaled'.

SpawnResultError
#

process.ts view source

SpawnResultError import type {SpawnResultError} from '@fuzdev/fuz_util/process.js';

Spawn failed before the process could run.

Note: child is still present because node:child_process.spawn returns a ChildProcess synchronously and then emits 'error' asynchronously — the handle exists but the OS process never started.

examples

ENOENT when command not found

kind

type 'error'

ok

type false

child

type ChildProcess

error

type Error

SpawnResultExited
#

process.ts view source

SpawnResultExited import type {SpawnResultExited} from '@fuzdev/fuz_util/process.js';

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

kind

type 'exited'

ok

type boolean

child

type ChildProcess

code

type number

SpawnResultSignaled
#

process.ts view source

SpawnResultSignaled import type {SpawnResultSignaled} from '@fuzdev/fuz_util/process.js';

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

kind

type 'signaled'

ok

type false

child

type ChildProcess

signal

type NodeJS.Signals

Depends on
#

Imported by
#