70ec6d01c2234d4c733ff16fcc19d96ef010208a2d2294180c6920a06045ea8fea55cdb61036fb9e916821c61bd160dc2d312280ac41c9fbe5e3c6fa0580f2 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. <img src="media/logo.svg" width="400">
  2. <br>
  3. [![Build Status](https://travis-ci.org/sindresorhus/execa.svg?branch=master)](https://travis-ci.org/sindresorhus/execa) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/execa/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/execa?branch=master)
  4. > Process execution for humans
  5. ## Why
  6. This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:
  7. - Promise interface.
  8. - [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.
  9. - Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform.
  10. - [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why)
  11. - Higher max buffer. 100 MB instead of 200 KB.
  12. - [Executes locally installed binaries by name.](#preferlocal)
  13. - [Cleans up spawned processes when the parent process dies.](#cleanup)
  14. - [Get interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal. [*(Async only)*](#execasyncfile-arguments-options)
  15. - [Can specify file and arguments as a single string without a shell](#execacommandcommand-options)
  16. - More descriptive errors.
  17. ## Install
  18. ```
  19. $ npm install execa
  20. ```
  21. ## Usage
  22. ```js
  23. const execa = require('execa');
  24. (async () => {
  25. const {stdout} = await execa('echo', ['unicorns']);
  26. console.log(stdout);
  27. //=> 'unicorns'
  28. })();
  29. ```
  30. ### Pipe the child process stdout to the parent
  31. ```js
  32. const execa = require('execa');
  33. execa('echo', ['unicorns']).stdout.pipe(process.stdout);
  34. ```
  35. ### Handling Errors
  36. ```js
  37. const execa = require('execa');
  38. (async () => {
  39. // Catching an error
  40. try {
  41. await execa('unknown', ['command']);
  42. } catch (error) {
  43. console.log(error);
  44. /*
  45. {
  46. message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
  47. errno: 'ENOENT',
  48. code: 'ENOENT',
  49. syscall: 'spawn unknown',
  50. path: 'unknown',
  51. spawnargs: ['command'],
  52. originalMessage: 'spawn unknown ENOENT',
  53. command: 'unknown command',
  54. stdout: '',
  55. stderr: '',
  56. all: '',
  57. failed: true,
  58. timedOut: false,
  59. isCanceled: false,
  60. killed: false
  61. }
  62. */
  63. }
  64. })();
  65. ```
  66. ### Cancelling a spawned process
  67. ```js
  68. const execa = require('execa');
  69. (async () => {
  70. const subprocess = execa('node');
  71. setTimeout(() => {
  72. subprocess.cancel();
  73. }, 1000);
  74. try {
  75. await subprocess;
  76. } catch (error) {
  77. console.log(subprocess.killed); // true
  78. console.log(error.isCanceled); // true
  79. }
  80. })()
  81. ```
  82. ### Catching an error with the sync method
  83. ```js
  84. try {
  85. execa.sync('unknown', ['command']);
  86. } catch (error) {
  87. console.log(error);
  88. /*
  89. {
  90. message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
  91. errno: 'ENOENT',
  92. code: 'ENOENT',
  93. syscall: 'spawnSync unknown',
  94. path: 'unknown',
  95. spawnargs: ['command'],
  96. originalMessage: 'spawnSync unknown ENOENT',
  97. command: 'unknown command',
  98. stdout: '',
  99. stderr: '',
  100. all: '',
  101. failed: true,
  102. timedOut: false,
  103. isCanceled: false,
  104. killed: false
  105. }
  106. */
  107. }
  108. ```
  109. ### Kill a process
  110. Using SIGTERM, and after 2 seconds, kill it with SIGKILL.
  111. ```js
  112. const subprocess = execa('node');
  113. setTimeout(() => {
  114. subprocess.kill('SIGTERM', {
  115. forceKillAfterTimeout: 2000
  116. });
  117. }, 1000);
  118. ```
  119. ## API
  120. ### execa(file, arguments, [options])
  121. Execute a file. Think of this as a mix of [`child_process.execFile()`](https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback) and [`child_process.spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options).
  122. No escaping/quoting is needed.
  123. Unless the [`shell`](#shell) option is used, no shell interpreter (Bash, `cmd.exe`, etc.) is used, so shell features such as variables substitution (`echo $PATH`) are not allowed.
  124. Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which:
  125. - is also a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).
  126. - exposes the following additional methods and properties.
  127. #### kill([signal], [options])
  128. Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal) except: if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.
  129. ##### options.forceKillAfterTimeout
  130. Type: `number | false`<br>
  131. Default: `5000`
  132. Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
  133. Can be disabled with `false`.
  134. #### cancel()
  135. Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.
  136. #### all
  137. Type: `ReadableStream | undefined`
  138. Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).
  139. This is `undefined` if either:
  140. - the [`all` option](#all-2) is `false` (the default value)
  141. - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
  142. ### execa.sync(file, [arguments], [options])
  143. Execute a file synchronously.
  144. Returns or throws a [`childProcessResult`](#childProcessResult).
  145. ### execa.command(command, [options])
  146. Same as [`execa()`](#execafile-arguments-options) except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.
  147. If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.
  148. The [`shell` option](#shell) must be used if the `command` uses shell-specific features, as opposed to being a simple `file` followed by its `arguments`.
  149. ### execa.commandSync(command, [options])
  150. Same as [`execa.command()`](#execacommand-command-options) but synchronous.
  151. Returns or throws a [`childProcessResult`](#childProcessResult).
  152. ### execa.node(scriptPath, [arguments], [options])
  153. Execute a Node.js script as a child process.
  154. Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):
  155. - the current Node version and options are used. This can be overridden using the [`nodePath`](#nodepath-for-node-only) and [`nodeOptions`](#nodeoptions-for-node-only) options.
  156. - the [`shell`](#shell) option cannot be used
  157. - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)
  158. ### childProcessResult
  159. Type: `object`
  160. Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.
  161. The child process [fails](#failed) when:
  162. - its [exit code](#exitcode) is not `0`
  163. - it was [killed](#killed) with a [signal](#signal)
  164. - [timing out](#timedout)
  165. - [being canceled](#iscanceled)
  166. - there's not enough memory or there are already too many child processes
  167. #### command
  168. Type: `string`
  169. The file and arguments that were run.
  170. #### exitCode
  171. Type: `number`
  172. The numeric exit code of the process that was run.
  173. #### stdout
  174. Type: `string | Buffer`
  175. The output of the process on stdout.
  176. #### stderr
  177. Type: `string | Buffer`
  178. The output of the process on stderr.
  179. #### all
  180. Type: `string | Buffer | undefined`
  181. The output of the process with `stdout` and `stderr` interleaved.
  182. This is `undefined` if either:
  183. - the [`all` option](#all-2) is `false` (the default value)
  184. - `execa.sync()` was used
  185. #### failed
  186. Type: `boolean`
  187. Whether the process failed to run.
  188. #### timedOut
  189. Type: `boolean`
  190. Whether the process timed out.
  191. #### isCanceled
  192. Type: `boolean`
  193. Whether the process was canceled.
  194. #### killed
  195. Type: `boolean`
  196. Whether the process was killed.
  197. #### signal
  198. Type: `string | undefined`
  199. The name of the signal that was used to terminate the process. For example, `SIGFPE`.
  200. If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.
  201. #### signalDescription
  202. Type: `string | undefined`
  203. A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.
  204. If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.
  205. #### originalMessage
  206. Type: `string | undefined`
  207. Original error message. This is `undefined` unless the child process exited due to an `error` event or a timeout.
  208. The `message` property contains both the `originalMessage` and some additional information added by Execa.
  209. ### options
  210. Type: `object`
  211. #### cleanup
  212. Type: `boolean`<br>
  213. Default: `true`
  214. Kill the spawned process when the parent process exits unless either:
  215. - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)
  216. - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit
  217. #### preferLocal
  218. Type: `boolean`<br>
  219. Default: `false`
  220. Prefer locally installed binaries when looking for a binary to execute.<br>
  221. If you `$ npm install foo`, you can then `execa('foo')`.
  222. #### localDir
  223. Type: `string`<br>
  224. Default: `process.cwd()`
  225. Preferred path to find locally installed binaries in (use with `preferLocal`).
  226. #### execPath
  227. Type: `string`<br>
  228. Default: `process.execPath` (current Node.js executable)
  229. Path to the Node.js executable to use in child processes.
  230. This can be either an absolute path or a path relative to the [`cwd` option](#cwd).
  231. Requires [`preferLocal`](#preferlocal) to be `true`.
  232. For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.
  233. #### buffer
  234. Type: `boolean`<br>
  235. Default: `true`
  236. Buffer the output from the spawned process. When set to `false`, you must read the output of [`stdout`](#stdout-1) and [`stderr`](#stderr-1) (or [`all`](#all) if the [`all`](#all-2) option is `true`). Otherwise the returned promise will not be resolved/rejected.
  237. If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), and [`error.all`](#all) will contain the buffered data.
  238. #### input
  239. Type: `string | Buffer | stream.Readable`
  240. Write some input to the `stdin` of your binary.<br>
  241. Streams are not allowed when using the synchronous methods.
  242. #### stdin
  243. Type: `string | number | Stream | undefined`<br>
  244. Default: `pipe`
  245. Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
  246. #### stdout
  247. Type: `string | number | Stream | undefined`<br>
  248. Default: `pipe`
  249. Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
  250. #### stderr
  251. Type: `string | number | Stream | undefined`<br>
  252. Default: `pipe`
  253. Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
  254. #### all
  255. Type: `boolean`<br>
  256. Default: `false`
  257. Add an `.all` property on the [promise](#all) and the [resolved value](#all-1). The property contains the output of the process with `stdout` and `stderr` interleaved.
  258. #### reject
  259. Type: `boolean`<br>
  260. Default: `true`
  261. Setting this to `false` resolves the promise with the error instead of rejecting it.
  262. #### stripFinalNewline
  263. Type: `boolean`<br>
  264. Default: `true`
  265. Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.
  266. #### extendEnv
  267. Type: `boolean`<br>
  268. Default: `true`
  269. Set to `false` if you don't want to extend the environment variables when providing the `env` property.
  270. ---
  271. Execa also accepts the below options which are the same as the options for [`child_process#spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options)/[`child_process#exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback)
  272. #### cwd
  273. Type: `string`<br>
  274. Default: `process.cwd()`
  275. Current working directory of the child process.
  276. #### env
  277. Type: `object`<br>
  278. Default: `process.env`
  279. Environment key-value pairs. Extends automatically from `process.env`. Set [`extendEnv`](#extendenv) to `false` if you don't want this.
  280. #### argv0
  281. Type: `string`
  282. Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified.
  283. #### stdio
  284. Type: `string | string[]`<br>
  285. Default: `pipe`
  286. Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
  287. #### serialization
  288. Type: `string`<br>
  289. Default: `'json'`
  290. Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execa.node()`](#execanodescriptpath-arguments-options):
  291. - `json`: Uses `JSON.stringify()` and `JSON.parse()`.
  292. - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
  293. Requires Node.js `13.2.0` or later.
  294. [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
  295. #### detached
  296. Type: `boolean`
  297. Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).
  298. #### uid
  299. Type: `number`
  300. Sets the user identity of the process.
  301. #### gid
  302. Type: `number`
  303. Sets the group identity of the process.
  304. #### shell
  305. Type: `boolean | string`<br>
  306. Default: `false`
  307. If `true`, runs `file` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.
  308. We recommend against using this option since it is:
  309. - not cross-platform, encouraging shell-specific syntax.
  310. - slower, because of the additional shell interpretation.
  311. - unsafe, potentially allowing command injection.
  312. #### encoding
  313. Type: `string | null`<br>
  314. Default: `utf8`
  315. Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.
  316. #### timeout
  317. Type: `number`<br>
  318. Default: `0`
  319. If timeout is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than timeout milliseconds.
  320. #### maxBuffer
  321. Type: `number`<br>
  322. Default: `100_000_000` (100 MB)
  323. Largest amount of data in bytes allowed on `stdout` or `stderr`.
  324. #### killSignal
  325. Type: `string | number`<br>
  326. Default: `SIGTERM`
  327. Signal value to be used when the spawned process will be killed.
  328. #### windowsVerbatimArguments
  329. Type: `boolean`<br>
  330. Default: `false`
  331. If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.
  332. #### windowsHide
  333. Type: `boolean`<br>
  334. Default: `true`
  335. On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.
  336. #### nodePath *(for `.node()` only)*
  337. Type: `string`<br>
  338. Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath)
  339. Node.js executable used to create the child process.
  340. #### nodeOptions *(for `.node()` only)*
  341. Type: `string[]`<br>
  342. Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv)
  343. List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.
  344. ## Tips
  345. ### Retry on error
  346. Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:
  347. ```js
  348. const pRetry = require('p-retry');
  349. const run = async () => {
  350. const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
  351. return results;
  352. };
  353. (async () => {
  354. console.log(await pRetry(run, {retries: 5}));
  355. })();
  356. ```
  357. ### Save and pipe output from a child process
  358. Let's say you want to show the output of a child process in real-time while also saving it to a variable.
  359. ```js
  360. const execa = require('execa');
  361. const subprocess = execa('echo', ['foo']);
  362. subprocess.stdout.pipe(process.stdout);
  363. (async () => {
  364. const {stdout} = await subprocess;
  365. console.log('child output:', stdout);
  366. })();
  367. ```
  368. ### Redirect output to a file
  369. ```js
  370. const execa = require('execa');
  371. const subprocess = execa('echo', ['foo'])
  372. subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))
  373. ```
  374. ### Redirect input from a file
  375. ```js
  376. const execa = require('execa');
  377. const subprocess = execa('cat')
  378. fs.createReadStream('stdin.txt').pipe(subprocess.stdin)
  379. ```
  380. ### Execute the current package's binary
  381. ```js
  382. const {getBinPathSync} = require('get-bin-path');
  383. const binPath = getBinPathSync();
  384. const subprocess = execa(binPath);
  385. ```
  386. `execa` can be combined with [`get-bin-path`](https://github.com/ehmicky/get-bin-path) to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the `package.json` `bin` field is correctly set up.
  387. ## Related
  388. - [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for `execa`
  389. ## Maintainers
  390. - [Sindre Sorhus](https://github.com/sindresorhus)
  391. - [@ehmicky](https://github.com/ehmicky)
  392. ---
  393. <div align="center">
  394. <b>
  395. <a href="https://tidelift.com/subscription/pkg/npm-execa?utm_source=npm-execa&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
  396. </b>
  397. <br>
  398. <sub>
  399. Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
  400. </sub>
  401. </div>