Process
Introduction
The process package is a small, fluent wrapper around running operating system commands from your application. You describe a command, run it, and get back a result object that holds the exit code, standard output and standard error. A failed command does not throw unless you ask it to, so you decide how to react.
It also has everything you need to test code that shells out: a fake that records every command, returns canned results, and can fail the test when something unexpected tries to run.
pnpm add @plinthjs/processRunning a process
Call Process.run() with a command and await the result.
import { Process } from '@plinthjs/process'
const result = await Process.run('echo hello && echo oops 1>&2')
result.successful() // => true
result.exitCode() // => 0
result.output() // => 'hello\n'
result.errorOutput() // => 'oops\n'
result.command() // => 'echo hello && echo oops 1>&2'A command is either a string or an array. A string runs through a shell, so pipes, && and variable expansion work. An array runs the program directly with the remaining items as its arguments, with no shell and no quoting issues.
await Process.run('ls -la | wc -l') // a shell string
await Process.run(['git', 'log', '--oneline', '-n', '5']) // a program and its argumentsPrefer the array form whenever any part of the command comes from user input.
Inspecting the result
The ProcessResult has these methods:
| Method | Returns |
|---|---|
successful() / failed() | Whether the exit code was 0 |
exitCode() | The exit code, or null if the process was killed or never started |
output() | Everything written to standard output |
errorOutput() | Everything written to standard error |
seeInOutput(text) | Whether standard output contains the text |
seeInErrorOutput(text) | Whether standard error contains the text |
command() | The command line that ran |
A command that cannot be found behaves differently depending on its form. A shell string reports exit code 127 with the shell's message on standard error. An array command that does not exist has an exit code of null, and the error message from the failed spawn is in errorOutput().
Throwing on failure
throw() throws a ProcessFailedError if the process failed and otherwise returns the result, so it chains. The error carries the full result and a message with the command, exit code and both outputs.
import { Process, ProcessFailedError } from '@plinthjs/process'
const result = await Process.run('exit 4')
try {
result.throw()
} catch (error) {
if (error instanceof ProcessFailedError) {
error.result.exitCode() // => 4
}
}
const ok = await Process.run('echo fine').then((r) => r.throw())throwIf(condition) throws only when the condition is true and the process failed.
Configuring a process
Process.run() is a shortcut. To configure a command first, start from one of the factory methods, chain what you need, and finish with run(). The factory methods are command, path, env, timeout, input and quietly, and each returns a PendingProcess you can keep chaining.
const result = await Process.path('/var/www')
.env({ NODE_ENV: 'production' })
.timeout(30)
.run('npm run build')Working directory
path(directory) sets the working directory.
const pwd = await Process.path('/tmp').run('pwd')
pwd.output() // => '/private/tmp\n' on macOS, '/tmp\n' elsewhereEnvironment variables
env(vars) adds variables to the child's environment. They are merged on top of the current process's environment, so the command still sees PATH and everything else. Calling env() more than once merges the values.
const result = await Process.env({ GREETING: 'yo' }).run('echo $GREETING')
result.output() // => 'yo\n'Standard input
input(text) writes the text to the process's standard input and closes it.
const result = await Process.input('piped in').run('cat')
result.output() // => 'piped in'Other spawn options
Process.options(...) (like Process.forever() and Process.idleTimeout(seconds)) starts a configured process, and the same methods exist on a PendingProcess. It passes any extra child_process.spawn options straight through, for example to set the user or to change how the shell is chosen.
await Process.command('echo $BASH_VERSION').options({ shell: '/bin/bash' }).run()Timeouts
Every process has a timeout of 60 seconds by default. When it is exceeded the process is killed with SIGKILL, the exit code is null, and a message is added to the error output.
const result = await Process.timeout(1).run('sleep 5')
result.exitCode() // => null
result.errorOutput() // => '\nThe process "sleep 5" exceeded the timeout of 1 seconds.'Change the limit with timeout(seconds), or remove it with forever() for something that should run as long as it needs.
await Process.command('npm run build').timeout(300).run()
await Process.command('tail -f storage/logs/app.log').forever().start()Idle timeout
idleTimeout(seconds) kills the process if it goes that long without writing anything to standard output or standard error. It is useful for commands that stream progress and should not stall silently. The idle clock restarts every time output arrives.
const result = await Process.command('sh -c "echo a; sleep 3"').idleTimeout(1).forever().run()
result.exitCode() // => null
result.output() // => 'a\n'
result.errorOutput() // => '\nThe process "sh -c "echo a; sleep 3"" exceeded the idle timeout of 1 seconds.'The overall timeout and the idle timeout can be used together. Whichever is hit first ends the process.
Reading output as it arrives
Pass a callback as the second argument to run() to be called for every chunk. The callback gets the stream name, 'stdout' or 'stderr', and the text.
await Process.run('echo one; echo two 1>&2', (type, chunk) => {
console.log(`${type}: ${chunk.trim()}`)
})
// stdout: one
// stderr: twoThe full output is still available on the result afterwards. If you do not want the callback to be called at all, add quietly() to the chain.
const result = await Process.quietly().run('echo hidden', () => {
// never called
})
result.output() // => 'hidden\n'Running in the background
start() begins a process and returns immediately with an InvokedProcess. Use it when you want to do something while the command runs, or stop it early.
const running = Process.start('sleep 10')
running.running() // => true
running.pid() // the operating system process id
const result = await running.stop() // sends SIGTERM and waits for the result
running.running() // => false| Method | What it does |
|---|---|
wait() | Resolves with the ProcessResult when the process ends |
running() | Whether the process has not finished yet |
pid() | The process id |
signal(signal?) | Sends a signal (default SIGTERM) and returns whether it was delivered |
stop(signal?) | Sends a signal if still running, then waits for the result |
latestOutput() | Standard output captured so far |
latestErrorOutput() | Standard error captured so far |
start() accepts the same output callback as run():
const build = Process.start('npm run build', (type, chunk) => process.stdout.write(chunk))
// ...do other work...
const result = await build.wait()A process that is stopped with a signal has an exit code of null.
Piping commands
Process.pipe() runs a list of commands in order and feeds each command's output to the next one as standard input. It returns the result of the last command, or the result of the first command that failed.
const result = await Process.pipe(['printf "b\\na\\nc\\n"', 'sort'])
result.output() // => 'a\nb\nc\n'Each step runs as its own process, one after another, rather than as a shell pipeline. Passing an empty list throws.
Running processes concurrently
Process.concurrently() runs several commands at the same time and waits for all of them. You add commands to the pool inside the callback. Each call to command() returns a PendingProcess, so you can configure that command individually.
const results = await Process.concurrently((pool) => {
pool.command('npm run lint')
pool.command('npm run typecheck').timeout(120)
pool.add(['npm', 'test']).path('/var/www/app')
})
results.length // => 3
results.successful() // => true only if every command exited with 0
results.failed() // => true if any command failed
results.get(0)?.output() // the first command's outputThe results are in the order you added the commands, not the order they finished. ProcessPoolResults is iterable, so you can loop over it:
for (const result of results) {
if (result.failed()) {
console.error(result.command(), result.errorOutput())
}
}Process.pool() is the same method under a second name.
Testing
Tests should not run real commands. Call Process.fake() to replace the runner. Every process that you start afterwards is recorded and answered with a stub instead of being executed. It returns a ProcessFake you assert against.
import { clearFake, Process } from '@plinthjs/process'
import { afterEach, expect, it } from 'vitest'
afterEach(() => clearFake())
it('reads the current branch', async () => {
const fake = Process.fake({
'git rev-parse --abbrev-ref HEAD': { output: 'main\n' },
})
const result = await Process.run('git rev-parse --abbrev-ref HEAD')
expect(result.output()).toBe('main\n')
fake.assertRan('git rev-parse --abbrev-ref HEAD')
})Always call clearFake() when the test ends, otherwise the fake stays in place for the next test.
Stubbing results
The object you pass to Process.fake() maps command patterns to results. A pattern is matched against the command line. It must match exactly, unless it contains *, which matches any run of characters. A stub can be a result object (output, errorOutput, exitCode) or a function that receives the command line and returns one.
const fake = Process.fake({
'git status': { output: 'clean' },
'ls *': { output: 'a\nb' },
'fail*': Process.fakeResult({ exitCode: 2, errorOutput: 'nope' }),
'echo *': (command) => ({ output: `ran: ${command}` }),
})Patterns are checked in the order you wrote them, and the first match wins. A command with no matching stub succeeds with empty output and exit code 0.
Asserting what ran
fake.assertRan('git status') // a command matching the pattern ran at least once
fake.assertRanTimes('ls *', 1) // ran exactly this many times
fake.assertNotRan('rm *') // never ran
fake.assertRan((command) => command.startsWith('echo')) // match with a predicate
fake.assertNothingRan() // no process at all ran
fake.recorded // every recorded process: { command, raw }The assertions throw an error with a readable message when they fail, so they work in any test runner.
Preventing stray processes
preventStrayProcesses() turns an unmatched command into an error. It is a safeguard against a test accidentally running something real that you forgot to stub.
const fake = Process.fake({ 'git status': { output: 'clean' } }).preventStrayProcesses()
await Process.run('git status') // fine
await Process.run('rm -rf build') // throws: Attempted process [rm -rf build] without a matching fakeThe error is thrown when the process is started, so it surfaces from run() and start() and fails the test.