Execa Async Child Process With Clean Output
Run child processes with execa to get parsed stdout and stderr, shell-free argument arrays, and non-zero exit codes surfaced as typed errors.
Code
import { execa } from 'execa';
async function runChecks() {
const result = await execa('git', ['diff', '--stat'], {
cwd: process.cwd(),
reject: false,
});
if (result.failed) {
console.error('command failed with code', result.exitCode);
console.error(result.stderr.trim());
return false;
}
console.log(result.stdout.trim());
return true;
}
const timeout = await execa('node', ['--version'], { timeout: 5000 });
console.log('node version:', timeout.stdout.trim());How it works
Execa Async Child Process With Clean Output is built around the function runChecks.
The async parts await their results, which keeps ordering predictable. The snippet’s external surface is execa, all of it via execa.
Watch out for
- External dependency:
execa— install it before running the snippet.
Putting it to use
The main signature reads async function runChecks()
The demo output is labeled (command failed with code, node version:), so every printed line maps back to its originating operation.
Core lines
const timeout = await execa('node', ['--version'], { timeout: 5000 });
const result = await execa('git', ['diff', '--stat'], {
cwd: process.cwd(),
reject: false,
});
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- Yes: `execa` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.