velt/process/child
import { exec, execSync, spawn } from "velt/process/child". Runs other programs. Programs are
found through PATH and arguments are passed as-is, with no shell quoting. A non-zero exit code
is not an error; failing to start the program throws IoError (e.g. ENOENT).
exec(program, args = [], opts: ExecOptions = {}): Promise<ExecResult>andexecSync(…).ExecOptions { cwd?; env?: Map; clearEnv?; input? }.execShell(command, opts)/execShellSync: run throughsh -corcmd /C. Never pass untrusted text.ExecResult { code: number; stdout; stderr; ok }:codeis128 + nwhen the process was killed by signaln.spawn(program, args = [], opts: SpawnOptions = {}): ChildProcess.SpawnOptionshascwd env clearEnv stdin stdout stderr; the stdio fields take"pipe","inherit"(the default) or"ignore". A child that inherits stdout or stderr prints after everything the program printed before starting it:spawnwrites buffered output to the OS first.ChildProcess { pid: number }: a handle likeTcpStream, released byclose().write(data),closeStdin()readStdout(max = 0)/readStderr:""means end of outputreadStdoutBytes/readStderrByteswait(): Promise<i64>,exitCode: i64 | nullkill(signal = "SIGTERM"),close()- Errors from awaited methods propagate to
catch.
ts
import { exec, execSync, spawn } from "velt/process/child";
const r = execSync("echo", ["hello", "world"]);
console.log(r.ok, r.code, r.stdout.trim()); // true 0 hello world
const sorted = await exec("sort", [], { input: "b\na\n" });
console.log(JSON.stringify(sorted.stdout)); // "a\nb\n"
const child = spawn("cat", [], { stdin: "pipe", stdout: "pipe" });
await child.write("piped\n");
await child.closeStdin();
console.log(JSON.stringify(await child.readStdout()), await child.wait()); // "piped\n" 0
child.close();Notes:
close()doesn't stop the program, which is reaped in the background;killit orwaitfor it. An unclosed handle leaks until the process exits.- On Windows every signal terminates the process.
- An unsupported signal name throws
IoError"EINVAL".