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.

JavascriptNodeCli Tooling

Code

javascriptsnippet
19 lines
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

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.