Installations
npm install execa
Developer
sindresorhus
Developer Guide
Module System
ESM
Min. Node Version
^18.19.0 || >=20.5.0
Typescript Support
Yes
Node Version
22.9.0
NPM Version
10.8.3
Statistics
6,889 Stars
801 Commits
221 Forks
40 Watching
1 Branches
61 Contributors
Updated on 26 Nov 2024
Languages
JavaScript (79.22%)
TypeScript (20.78%)
Total Downloads
Cumulative downloads
Total Downloads
15,336,502,250
Last day
-4%
18,341,742
Compared to previous day
Last week
2.9%
99,045,330
Compared to previous week
Last month
16.9%
398,749,133
Compared to previous month
Last year
16.7%
4,107,394,527
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Process execution for humans
Execa runs commands in your script, application or library. Unlike shells, it is optimized for programmatic usage. Built on top of the child_process
core module.
One of the maintainers @ehmicky is looking for a remote full-time position. Specialized in Node.js back-ends and CLIs, he led Netlify Build, Plugins and Configuration for 2.5 years. Feel free to contact him on his website or on LinkedIn!
Features
- Simple syntax: promises and template strings, like
zx
. - Script interface.
- No escaping nor quoting needed. No risk of shell injection.
- Execute locally installed binaries without
npx
. - Improved Windows support: shebangs,
PATHEXT
, graceful termination, and more. - Detailed errors, verbose mode and custom logging, for debugging.
- Pipe multiple subprocesses better than in shells: retrieve intermediate results, use multiple sources/destinations, unpipe.
- Split the output into text lines, or iterate progressively over them.
- Strip unnecessary newlines.
- Pass any input to the subprocess: files, strings,
Uint8Array
s, iterables, objects and almost any other type. - Return almost any type from the subprocess, or redirect it to files.
- Get interleaved output from
stdout
andstderr
similar to what is printed on the terminal. - Retrieve the output programmatically and print it on the console at the same time.
- Transform or filter the input and output with simple functions.
- Pass Node.js streams or web streams to subprocesses, or convert subprocesses to a stream.
- Exchange messages with the subprocess.
- Ensure subprocesses exit even when they intercept termination signals, or when the current process ends abruptly.
Install
1npm install execa
Documentation
Execution:
- ▶️ Basic execution
- 💬 Escaping/quoting
- 💻 Shell
- 📜 Scripts
- 🐢 Node.js files
- 🌐 Environment
- ❌ Errors
- 🏁 Termination
Input/output:
- 🎹 Input
- 📢 Output
- 📃 Text lines
- 🤖 Binary data
- 🧙 Transforms
Advanced usage:
- 🔀 Piping multiple subprocesses
- ⏳️ Streams
- 📞 Inter-process communication
- 🐛 Debugging
- 📎 Windows
- 🔍 Difference with Bash and zx
- 🐭 Small packages
- 🤓 TypeScript
- 📔 API reference
Examples
Execution
Simple syntax
1import {execa} from 'execa'; 2 3const {stdout} = await execa`npm run build`; 4// Print command's output 5console.log(stdout);
Script
1import {$} from 'execa'; 2 3const {stdout: name} = await $`cat package.json`.pipe`grep name`; 4console.log(name); 5 6const branch = await $`git branch --show-current`; 7await $`dep deploy --branch=${branch}`; 8 9await Promise.all([ 10 $`sleep 1`, 11 $`sleep 2`, 12 $`sleep 3`, 13]); 14 15const directoryName = 'foo bar'; 16await $`mkdir /tmp/${directoryName}`;
Local binaries
1$ npm install -D eslint
1await execa({preferLocal: true})`eslint`;
Pipe multiple subprocesses
1const {stdout, pipedFrom} = await execa`npm run build` 2 .pipe`sort` 3 .pipe`head -n 2`; 4 5// Output of `npm run build | sort | head -n 2` 6console.log(stdout); 7// Output of `npm run build | sort` 8console.log(pipedFrom[0].stdout); 9// Output of `npm run build` 10console.log(pipedFrom[0].pipedFrom[0].stdout);
Input/output
Interleaved output
1const {all} = await execa({all: true})`npm run build`; 2// stdout + stderr, interleaved 3console.log(all);
Programmatic + terminal output
1const {stdout} = await execa({stdout: ['pipe', 'inherit']})`npm run build`; 2// stdout is also printed to the terminal 3console.log(stdout);
Simple input
1const getInputString = () => { /* ... */ }; 2const {stdout} = await execa({input: getInputString()})`sort`; 3console.log(stdout);
File input
1// Similar to: npm run build < input.txt 2await execa({stdin: {file: 'input.txt'}})`npm run build`;
File output
1// Similar to: npm run build > output.txt 2await execa({stdout: {file: 'output.txt'}})`npm run build`;
Split into text lines
1const {stdout} = await execa({lines: true})`npm run build`; 2// Print first 10 lines 3console.log(stdout.slice(0, 10).join('\n'));
Streaming
Iterate over text lines
1for await (const line of execa`npm run build`) { 2 if (line.includes('WARN')) { 3 console.warn(line); 4 } 5}
Transform/filter output
1let count = 0; 2 3// Filter out secret lines, then prepend the line number 4const transform = function * (line) { 5 if (!line.includes('secret')) { 6 yield `[${count++}] ${line}`; 7 } 8}; 9 10await execa({stdout: transform})`npm run build`;
Web streams
1const response = await fetch('https://example.com'); 2await execa({stdin: response.body})`sort`;
Convert to Duplex stream
1import {execa} from 'execa'; 2import {pipeline} from 'node:stream/promises'; 3import {createReadStream, createWriteStream} from 'node:fs'; 4 5await pipeline( 6 createReadStream('./input.txt'), 7 execa`node ./transform.js`.duplex(), 8 createWriteStream('./output.txt'), 9);
IPC
Exchange messages
1// parent.js 2import {execaNode} from 'execa'; 3 4const subprocess = execaNode`child.js`; 5await subprocess.sendMessage('Hello from parent'); 6const message = await subprocess.getOneMessage(); 7console.log(message); // 'Hello from child'
1// child.js 2import {getOneMessage, sendMessage} from 'execa'; 3 4const message = await getOneMessage(); // 'Hello from parent' 5const newMessage = message.replace('parent', 'child'); // 'Hello from child' 6await sendMessage(newMessage);
Any input type
1// main.js 2import {execaNode} from 'execa'; 3 4const ipcInput = [ 5 {task: 'lint', ignore: /test\.js/}, 6 {task: 'copy', files: new Set(['main.js', 'index.js']), 7}]; 8await execaNode({ipcInput})`build.js`;
1// build.js 2import {getOneMessage} from 'execa'; 3 4const ipcInput = await getOneMessage();
Any output type
1// main.js
2import {execaNode} from 'execa';
3
4const {ipcOutput} = await execaNode`build.js`;
5console.log(ipcOutput[0]); // {kind: 'start', timestamp: date}
6console.log(ipcOutput[1]); // {kind: 'stop', timestamp: date}
1// build.js 2import {sendMessage} from 'execa'; 3 4const runBuild = () => { /* ... */ }; 5 6await sendMessage({kind: 'start', timestamp: new Date()}); 7await runBuild(); 8await sendMessage({kind: 'stop', timestamp: new Date()});
Graceful termination
1// main.js 2import {execaNode} from 'execa'; 3 4const controller = new AbortController(); 5setTimeout(() => { 6 controller.abort(); 7}, 5000); 8 9await execaNode({ 10 cancelSignal: controller.signal, 11 gracefulCancel: true, 12})`build.js`;
1// build.js 2import {getCancelSignal} from 'execa'; 3 4const cancelSignal = await getCancelSignal(); 5const url = 'https://example.com/build/info'; 6const response = await fetch(url, {signal: cancelSignal});
Debugging
Detailed error
1import {execa, ExecaError} from 'execa'; 2 3try { 4 await execa`unknown command`; 5} catch (error) { 6 if (error instanceof ExecaError) { 7 console.log(error); 8 } 9 /* 10 ExecaError: Command failed with ENOENT: unknown command 11 spawn unknown ENOENT 12 at ... 13 at ... { 14 shortMessage: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT', 15 originalMessage: 'spawn unknown ENOENT', 16 command: 'unknown command', 17 escapedCommand: 'unknown command', 18 cwd: '/path/to/cwd', 19 durationMs: 28.217566, 20 failed: true, 21 timedOut: false, 22 isCanceled: false, 23 isTerminated: false, 24 isMaxBuffer: false, 25 code: 'ENOENT', 26 stdout: '', 27 stderr: '', 28 stdio: [undefined, '', ''], 29 pipedFrom: [] 30 [cause]: Error: spawn unknown ENOENT 31 at ... 32 at ... { 33 errno: -2, 34 code: 'ENOENT', 35 syscall: 'spawn unknown', 36 path: 'unknown', 37 spawnargs: [ 'command' ] 38 } 39 } 40 */ 41}
Verbose mode
1await execa`npm run build`; 2await execa`npm run test`;
Custom logging
1import {execa as execa_} from 'execa'; 2import {createLogger, transports} from 'winston'; 3 4// Log to a file using Winston 5const transport = new transports.File({filename: 'logs.txt'}); 6const logger = createLogger({transports: [transport]}); 7const LOG_LEVELS = { 8 command: 'info', 9 output: 'verbose', 10 ipc: 'verbose', 11 error: 'error', 12 duration: 'info', 13}; 14 15const execa = execa_({ 16 verbose(verboseLine, {message, ...verboseObject}) { 17 const level = LOG_LEVELS[verboseObject.type]; 18 logger[level](message, verboseObject); 19 }, 20}); 21 22await execa`npm run build`; 23await execa`npm run test`;
Related
- nano-spawn - Like Execa but smaller
- gulp-execa - Gulp plugin for Execa
- nvexeca - Run Execa using any Node.js version
Maintainers
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
14 commit(s) and 11 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
- Info: security policy file detected: .github/security.md:1
- Info: Found linked content: .github/security.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/security.md:1
- Info: Found text in security policy: .github/security.md:1
Reason
license file detected
Details
- Info: project has a license file: license:0
- Info: FSF or OSI recognized license: MIT License: license:0
Reason
0 existing vulnerabilities detected
Reason
binaries present in source code
Details
- Warn: binary detected: test/fixtures/fast-exit-darwin:1
- Warn: binary detected: test/fixtures/fast-exit-linux:1
Reason
Found 23/30 approved changesets -- score normalized to 7
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/execa/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/execa/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/execa/main.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/main.yml:30: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/execa/main.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/main.yml:38: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/execa/main.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:30
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 2 third-party GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 23 are checked with a SAST tool
Score
5.5
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to execa
safe-execa
Like execa but prevents binary planting attacks on Windows
nvexeca
nvm + execa = nvexeca
@esm2cjs/execa
Process execution for humans. This is a fork of sindresorhus/execa, but with CommonJS support.
@form8ion/execa-wrapper
wrapper to expose execa as a dual-mode package