A non-zero exit code resolves, so callers decide what counts as failure. A timeout, too much output, or a failure to start rejects with PROCESS_TIMED_OUT, PROCESS_OUTPUT_TOO_LARGE, or PROCESS_START_FAILED. A timeout that isn’t a positive number of at most 2,147,483 seconds, or an output limit that isn’t a positive safe integer, such as a computed budget that ran out, rejects with INVALID_PROCESS_OPTIONS before anything starts. With encoding: 'buffer', stdout and stderr are the bytes the process wrote, for output that may not be valid UTF-8, such as file names.
Run an interactive command in the current terminal:
The child inherits stdin, stdout and stderr. The result includes a nonzero exit code or the signal that stopped the child. A launch failure rejects with PROCESS_START_FAILED. Terminal interrupts follow the current process group’s signal policy.
Start a long-running process that you own, and stop it together with everything it started:
ts
import { createShutdownSignal, startProcess, stopProcessTree } from 'jg-process';const server = startProcess({ command: 'node', args: ['server.js'], cwd: 'apps/api' });const shutdown = createShutdownSignal(); // Ctrl+C or SIGTERM, which sets the exit code to 130 or 143shutdown.signal.addEventListener('abort', () => void stopProcessTree(server), { once: true });
createShutdownSignal turns SIGINT and SIGTERM, or the signals you pass, into an AbortSignal that aborts with PROCESS_INTERRUPTED at the first one, so one signal stops a script’s or a service’s work. It sets process.exitCode to 128 plus the signal’s number, as a shell reports a process the signal stopped, unless setExitCode is false, and calls onSignal once, ignoring what it throws. It never calls process.exit, so the process exits once its work stops. A second signal is ignored, or, with forceOnRepeat, stops the process at once, for a shutdown that hangs. With disconnect: true, a child started with an IPC channel, such as by fork, also shuts down as with SIGTERM when its parent closes the channel or dies. dispose stops listening. On Windows, Ctrl+C sends SIGINT, but SIGTERM is never delivered.
Start a server and wait until it answers, or stop everything it started when it doesn’t:
Reserve a free port before handing it to a server, keeping the preferred one when it’s free:
ts
import { reservePort } from 'jg-process';const reservation = await reservePort({ preferredPort: 3000 }); // 3000, or another free portawait reservation.release(); // right before the server binds it
Write a CLI script that parses its options strictly, reads piped input, and runs only when executed:
parseStrictArgs refuses unknown options, positional arguments, an option given twice that isn’t multiple, an empty value, and a missing required option, with INVALID_ARGUMENTS and data.option naming it. isMainModule compares real paths, so a script started through a symbolic link, such as an npm bin entry, counts. isProcessRunning(pid) tells whether a process, such as a lock’s owner, is still running.
Generated from TSDoc
API reference
Every export of [email protected], 43 in all, with its signature, its errors, and an example.
Turns the signals that ask a process to stop, SIGINT and SIGTERM by default, into an AbortSignal, so a script or a service passes one signal to the work it shuts down. The first signal aborts it with PROCESS_INTERRUPTED, sets process.exitCode to 128 plus the signal's number, 130 for SIGINT and 143 for SIGTERM, as a shell reports it, and calls onSignal. It never calls process.exit: the process exits once the work stops. Later signals are ignored, or, with forceOnRepeat, stop the process at once, as they would without a listener. On Windows, Ctrl+C sends SIGINT, but SIGTERM is never delivered. With disconnect, a child started with an IPC channel, such as by fork, also shuts down as with SIGTERM when its parent closes the channel or dies, at once when it's already closed. dispose stops listening.
The signals, what runs at the first one, and how later ones behave.
Defaults to {}.
Returns
IShutdownSignal
The shutdown signal.
Throws
INVALID_SIGNALThe shutdown needs a non-empty list of signals Node.js can listen for, such as SIGINT, other than SIGKILL and SIGSTOP, and an onSignal that's a function when it's given.
Example
import { createShutdownSignal } from 'jg-process';declare const drainQueue: (signal: AbortSignal) => Promise<void>;const shutdown = createShutdownSignal({ forceOnRepeat: true });await drainQueue(shutdown.signal); // stops at Ctrl+C, and the process exits with 130shutdown.dispose();
Tells whether the module is the script Node.js was started with, such as a CLI file that should run its command only when executed, not when a test imports it. It compares real paths, so a script started through a symbolic link, such as an npm bin entry, still counts.
Signature
isMainModule(importMetaUrl: string): boolean
Parameters
importMetaUrlstring
The module's import.meta.url.
Returns
boolean
Whether the module is the entry script, or false when either path can't be resolved.
Example
import { isMainModule } from 'jg-process';if (isMainModule(import.meta.url)) { // run the command}
Tells whether a process with this id is running on this machine, such as the owner a lock file names. It sends signal 0, which checks without signalling, and treats only ESRCH, no such process, as gone: a process that belongs to another user still counts as running.
Signature
isProcessRunning(pid: number): boolean
Parameters
pidnumber
The process id.
Returns
boolean
Whether the process is running.
Throws
INVALID_PROCESS_IDThe process id must be a positive safe integer.
Example
import { isProcessRunning } from 'jg-process';isProcessRunning(process.pid); // true
Parses a command's arguments strictly, as util.parseArgs does with strict: true and no positionals, and also refuses what parseArgs lets through: an option given twice that isn't multiple, an empty string value, and a missing required option. A missing flag is false, a missing multiple option an empty array, and a missing optional string undefined.
Reads the process's stdin to its end, such as the input a CLI is piped. It refuses more than maxBytes, destroying stdin once the input passes the limit, and stops when the signal aborts.
Reads a stream to its end, such as a request body or a socket's message, into one buffer. It refuses more than maxBytes the moment the content passes the limit, and stops when the signal aborts. A refused or stopped read leaves the stream open and paused, so its owner can still answer, such as with a 413, before it closes the stream. Start reading before the stream ends.
Reserves a free TCP port by listening on it, so nothing else can take it until it's released, such as before passing it to a dev server or a test fixture. The preferred port is kept when it's free, and any free port is reserved when it's taken. Connections to the reserved port are closed at once, and the reservation doesn't keep the process running.
A child process that needs the port itself can't bind it while it's reserved, so release it right before starting the child. Another process can take the port in between.
The preferred port and the address. The address defaults to 127.0.0.1.
Defaults to {}.
Returns
Promise<IPortReservation>
A promise that resolves to the reservation.
Throws
INVALID_PORTThe preferred port must be an integer from 1 to 65535.
PORT_RESERVATION_FAILEDThe port couldn't be reserved.
Example
import { reservePort } from 'jg-process';const reservation = await reservePort({ preferredPort: 3000 });console.log(`The port is ${reservation.port}`); // 3000, or another free port when it's takenawait reservation.release();
Builds the command that runs a package manager with the given arguments, without a shell, so it can be passed to runProcess or startProcess as it is on Windows, macOS, and Linux. It looks, in order, at: 1. npm_execpath, which a package manager sets for the scripts it runs, when it names the requested package manager, or any one when none is requested 2. the package manager installed in the project, resolved from cwd 3. PATH: an executable on POSIX, and on Windows an .exe, or a .cmd or .ps1 shim whose script it runs through Node.js, because Node.js refuses to spawn a .cmd file without a shell
A JavaScript entry, such as pnpm.cjs, runs through the current Node.js. Without a requested package manager or npm_execpath, there's nothing to look for, so it throws.
Runs a command without a shell, inheriting all three standard streams in the caller's process group. The terminal handles interrupts for the group. The caller retains its own signal policy.
Runs a command to completion and resolves with its exit code, signal and output, decoded as UTF-8, or as the bytes the process wrote with encoding: 'buffer'. It runs without a shell and, on POSIX, as the leader of its own process group.
Every exit resolves, whatever its code: callers decide which codes are acceptable, so process output never ends up in an error message. The call rejects only when the command can't start, the timeout passes, the output exceeds maxOutputBytes, or the signal aborts; in those cases the process tree is stopped first, so the rejection can arrive up to the grace period plus two seconds after the trigger on POSIX, and up to 30 seconds after it on Windows, where the stop lists the tree, runs taskkill, and waits for every process to exit, each within 10 seconds.
Input that the child never reads is discarded without an error. When the child exits, descendants left in its process group are stopped. If one that couldn't be reached, such as a descendant that left the group with setsid or one orphaned on Windows, keeps stdout or stderr open for longer than the grace period, the call rejects instead of hanging.
Because the child leads its own group, a terminal's Ctrl+C reaches only the parent: CLIs should abort the signal when they receive SIGINT or SIGTERM.
Starts a long-running child that the caller owns, without a shell and, on POSIX, as the leader of its own process group, so stopProcessTree can later stop it together with its descendants. Because the child leads its own group, a terminal's Ctrl+C reaches only the parent: CLIs should stop the child when they receive SIGINT or SIGTERM. A command that can't start emits an 'error' event on the returned child.
Starts a long-running process, such as a dev server, with startProcess, and resolves with it once it's ready: its port accepts connections, its URL answers, or a probe returns a value other than null, undefined, or false. When it exits, fails to start, isn't ready in time, or the signal aborts, its whole process tree is stopped before the call rejects, so nothing is left running.
Stops a child started by startProcess or runProcess together with its descendants, and resolves once they are gone. It resolves immediately for a child without a pid.
On POSIX, it sends SIGTERM to the child's process group, waits up to the grace period, then sends SIGKILL and waits up to two more seconds. It is designed for children that lead their own process group, as startProcess and runProcess start them; for any other child, it signals the child alone. Descendants that start their own session or process group, for example with setsid, aren't stopped.
On Windows, it lists the child's descendants with PowerShell's Get-CimInstance, runs taskkill /T /F, and waits up to ten seconds until the child and each listed descendant have exited, so their working directories can be removed once it resolves. taskkill reaches only descendants of a root process that is still running: when the root has already exited, it resolves and orphaned descendants may remain. Without PowerShell, it waits for the child alone.
A promise that resolves once the process tree is gone.
Throws
PROCESS_TREE_SURVIVEDThe process tree is still running after it was force-stopped.
Example
import { startProcess, stopProcessTree } from 'jg-process';const server = startProcess('node', ['server.js']);await stopProcessTree(server, 10); // SIGTERM, then SIGKILL after 10 seconds
Waits until a TCP port accepts connections, such as a database or a dev server that a script started, probing every intervalSeconds until timeoutSeconds pass. With a child, its exit or failure to start ends the wait at once, since it can no longer become ready.
Waits until a URL answers in a way that means ready, by default with a 2xx status, such as a health endpoint. Redirects aren't followed, a network error means not ready yet, and every response's body is discarded. With a child, its exit or failure to start ends the wait at once.
The package manager to run. Defaults to the one running the current package script, which npm_execpath names; without one, a package manager has to be named.
envproperty
NodeJS.ProcessEnv
the environment that holds npm_execpath and PATH. Defaults to process.env
cwdproperty
string
the directory a local install is resolved from. Defaults to the current one
the signals that start the shutdown. Defaults to SIGINT and SIGTERM
onSignalproperty
(signal: NodeJS.Signals) => unknown
runs once, with the first signal, after the abort; what it throws or rejects with is ignored
setExitCodeproperty
boolean
whether the first signal sets process.exitCode to 128 plus its number, as a shell reports a process the signal stopped. Defaults to true
forceOnRepeatproperty
boolean
whether a second signal stops the process at once, as Node.js does without a listener, for a shutdown that hangs. Defaults to false, which ignores later signals
disconnectproperty
boolean
whether the IPC channel to the parent closing starts the shutdown too, as SIGTERM does, such as for a child whose parent died without signalling it. Defaults to false
the values parseStrictArgs returns for its options: false for a missing flag, an empty array for a missing repeated option, and undefined for a missing optional string