Introduction to Execa
Execa is a modern JavaScript library that enhances the experience of running shell commands. It’s built on top of Node.js’ child_process module, providing a friendly Promise-based API. Execa offers better defaults, async process execution, and various powerful features. Let’s dive into its numerous capabilities and how to harness them in your applications.
Basic Examples
const execa = require('execa');
// Run a simple command async function runCommand() { const { stdout } = await execa('echo', ['Hello, World!']); console.log(stdout); // => Hello, World! }
runCommand();
Advanced Examples
Streaming Output
const execa = require('execa');
// Stream output const subprocess = execa('echo', ['streaming...']); subprocess.stdout.pipe(process.stdout);
Handling Errors
const execa = require('execa');
async function runCommand() { try { await execa('nonexistent-cmd'); } catch (error) { console.error('An error occurred:', error); } }
runCommand();
Environment Variables
const execa = require('execa');
// Set environment variables async function runCommand() { const { stdout } = await execa('printenv', ['MY_VAR'], { env: { MY_VAR: 'MY_VALUE' } }); console.log(stdout); // => MY_VALUE }
runCommand();
App Example
Let’s illustrate a real-world application where Execa is used to script Git operations within a Node.js app.
const execa = require('execa');
async function cloneRepository(url) { await execa('git', ['clone', url]); console.log(`Cloned ${url}`); }
async function fetchAllCommits(repositoryPath) { const { stdout } = await execa('git', ['log', '--pretty=oneline'], { cwd: repositoryPath }); console.log(`Commits:
${stdout}`); }
async function main() { const repoUrl = 'https://github.com/user/repository.git'; const repoPath = './repository';
await cloneRepository(repoUrl); await fetchAllCommits(repoPath); }
main();
In this example, we demonstrate how to clone a Git repository and fetch all commits using Execa.
Hash: e1d4ca802d959027d79bc2eef0fbd107c4e121554eced8bd7452f324474d5ce5