GitHub 0
Skip to content

Exec

Run a command to the end without throwing on its exit code, with support for timeouts and cancellation.

fleethosts/exec runs local commands. The hosts API is built on it, and you can use it on its own.

import { exec } from "fleethosts/exec";

const run = await exec("git", ["status", "--short"], { cwd: "/srv/app", timeoutMs: 10_000 });
if (run.code === 0) console.log(run.stdout);
else console.error(run.timedOut ? "too slow" : run.stderr);
ts

exec(command, args, options) runs the command to the end and returns an ExecResult. A non-zero exit doesn't throw. A command that can't start doesn't throw either: spawnError holds the code, such as ENOENT when it isn't installed.

FieldWhat it holds
codeThe exit code, or null when a signal ended the command or it never started
stdout, stderrThe end of the output
timedOutThe command ran past timeoutMs and was stopped
truncatedThe output went past maxOutput, so only its end was kept
spawnErrorWhy the command couldn't start

args go to the command as they are, with no shell, unless you pass shell: true.

OptionDefaultWhat it does
cwdthe current folderWhere the command runs
envprocess.envThe whole environment, not additions to it
input""Written to stdin, which then closes
holdStdinfalseKeep stdin open after input, so the command sees when this process is gone
timeoutMsnoneStop the command after this many milliseconds
shellfalseRun through the shell
signalnoneAn AbortSignal that stops the command
keepTerminalfalseKeep the terminal, so the command can prompt
maxOutput1 MiBCharacters of stdout and of stderr to keep, from the end
stderrHead0Characters of stderr to keep from the start as well

With stderrHead, both ends of stderr survive, joined by a [...] line where the middle went.

When timeoutMs passes, exec kills the command and resolves with timedOut: true. It resolves once the command exits, even when something the command started still holds its output open.

Pass a signal to stop a command from outside. When the signal aborts, the command and everything it started are killed, and the promise rejects with signal.reason. A signal that has already aborted rejects before anything starts.

const controller = new AbortController();
setTimeout(() => controller.abort(new Error("cancelled")), 5_000);

await exec("sh", ["-c", "make all"], { signal: controller.signal }).catch((error) => {
  console.error(error.message); // "cancelled"
});
ts

withExecSignal(signal, work) gives the signal to every exec that runs inside work, however deep. A command that also has its own signal stops when either aborts.

import { exec, withExecSignal } from "fleethosts/exec";

const controller = new AbortController();
await withExecSignal(controller.signal, async (settled) => {
  await Promise.allSettled([exec("sleep", ["5"]), exec("sleep", ["10"])]);
  await settled();
});
ts

settled() waits for every command the job started to finish, including ones it didn't await. Call it before you clean up files they use.

execSignal() returns the signal of the job you are in, or undefined.

On macOS and Linux, a command runs in a process group of its own when it has a signal (its own, or a job's), when shell is true, or when keepTerminal can't be honoured. Stopping kills the whole group, so a shell's children stop with it.

A plain command with no signal stays in this process's group, so ssh and git can still prompt on the terminal. A timeout kills only that command.

When this process gets SIGINT, SIGTERM or SIGHUP while such commands run, it passes the signal on to them, then ends with that signal. Ctrl-C stops your commands, not only Node.

With keepTerminal: true, the command stays in this group and keeps the terminal. To stop it, fleethosts finds what it started in the process table, freezes each process with SIGSTOP, then kills them. On Linux this needs /proc to show this process's PID namespace; where it doesn't, the command gets its own group and loses the terminal.

On Windows, taskkill /t stops the command and what it started.

stopAll() stops the commands exec is still tracking, using the process and group rules above. With default exec() options and no job signal on macOS or Linux, only the direct child is killed; its descendants may survive. You can call it on exit, but it does not guarantee process-tree cleanup:

import { stopAll } from "fleethosts/exec";

process.on("exit", stopAll);
ts

git(args, options) runs git with no prompts, and throws a GitError on a non-zero exit unless allowFail is true.

import { git, gitOut } from "fleethosts/exec";

const branch = await gitOut(["rev-parse", "--abbrev-ref", "HEAD"], "/srv/app");
const { code } = await git(["diff", "--quiet"], { cwd: "/srv/app", allowFail: true });
ts

It sets GIT_TERMINAL_PROMPT=0, empties GIT_ASKPASS and SSH_ASKPASS, runs with LC_ALL=C, and drops GIT_CONFIG. An http transfer under 1 KB/s for a minute ends. The timeout defaults to two minutes, and the output is never cut.

OptionWhat it does
noFetchFetch nothing from a remote, not even a lazy fetch in a partial clone
indexFileUse another index file
inputWritten to stdin

A GitError has the args and the result. Its message says git isn't installed, that it timed out, or what git printed.

program(variable, fallback) returns the command to run: fallback, or the program the environment variable names. A .js or .mjs file runs with the current Node. notInstalled(command, fallback, variable) writes the error for a missing one.

import { exec, notInstalled, program } from "fleethosts/exec";

const { command, prefix } = program("MYTOOL_RSYNC", "rsync");
const run = await exec(command, [...prefix, "-a", "src/", "backup/"]);
if (run.spawnError === "ENOENT") throw new Error(notInstalled(command, "rsync", "MYTOOL_RSYNC"));
ts