You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

327 lines
8.1 KiB

4 years ago
  1. # execa [![Build Status: Linux](https://travis-ci.org/sindresorhus/execa.svg?branch=master)](https://travis-ci.org/sindresorhus/execa) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/x5ajamxtjtt93cqv/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/execa/branch/master) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/execa/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/execa?branch=master)
  2. > A better [`child_process`](https://nodejs.org/api/child_process.html)
  3. ## Why
  4. - Promise interface.
  5. - [Strips EOF](https://github.com/sindresorhus/strip-eof) from the output so you don't have to `stdout.trim()`.
  6. - Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform.
  7. - [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why)
  8. - Higher max buffer. 10 MB instead of 200 KB.
  9. - [Executes locally installed binaries by name.](#preferlocal)
  10. - [Cleans up spawned processes when the parent process dies.](#cleanup)
  11. ## Install
  12. ```
  13. $ npm install execa
  14. ```
  15. <a href="https://www.patreon.com/sindresorhus">
  16. <img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
  17. </a>
  18. ## Usage
  19. ```js
  20. const execa = require('execa');
  21. (async () => {
  22. const {stdout} = await execa('echo', ['unicorns']);
  23. console.log(stdout);
  24. //=> 'unicorns'
  25. })();
  26. ```
  27. Additional examples:
  28. ```js
  29. const execa = require('execa');
  30. (async () => {
  31. // Pipe the child process stdout to the current stdout
  32. execa('echo', ['unicorns']).stdout.pipe(process.stdout);
  33. // Run a shell command
  34. const {stdout} = await execa.shell('echo unicorns');
  35. //=> 'unicorns'
  36. // Catching an error
  37. try {
  38. await execa.shell('exit 3');
  39. } catch (error) {
  40. console.log(error);
  41. /*
  42. {
  43. message: 'Command failed: /bin/sh -c exit 3'
  44. killed: false,
  45. code: 3,
  46. signal: null,
  47. cmd: '/bin/sh -c exit 3',
  48. stdout: '',
  49. stderr: '',
  50. timedOut: false
  51. }
  52. */
  53. }
  54. })();
  55. // Catching an error with a sync method
  56. try {
  57. execa.shellSync('exit 3');
  58. } catch (error) {
  59. console.log(error);
  60. /*
  61. {
  62. message: 'Command failed: /bin/sh -c exit 3'
  63. code: 3,
  64. signal: null,
  65. cmd: '/bin/sh -c exit 3',
  66. stdout: '',
  67. stderr: '',
  68. timedOut: false
  69. }
  70. */
  71. }
  72. ```
  73. ## API
  74. ### execa(file, [arguments], [options])
  75. Execute a file.
  76. Think of this as a mix of `child_process.execFile` and `child_process.spawn`.
  77. Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.
  78. ### execa.stdout(file, [arguments], [options])
  79. Same as `execa()`, but returns only `stdout`.
  80. ### execa.stderr(file, [arguments], [options])
  81. Same as `execa()`, but returns only `stderr`.
  82. ### execa.shell(command, [options])
  83. Execute a command through the system shell. Prefer `execa()` whenever possible, as it's both faster and safer.
  84. Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess).
  85. The `child_process` instance is enhanced to also be promise for a result object with `stdout` and `stderr` properties.
  86. ### execa.sync(file, [arguments], [options])
  87. Execute a file synchronously.
  88. Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options).
  89. This method throws an `Error` if the command fails.
  90. ### execa.shellSync(file, [options])
  91. Execute a command synchronously through the system shell.
  92. Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options).
  93. ### options
  94. Type: `Object`
  95. #### cwd
  96. Type: `string`<br>
  97. Default: `process.cwd()`
  98. Current working directory of the child process.
  99. #### env
  100. Type: `Object`<br>
  101. Default: `process.env`
  102. Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.
  103. #### extendEnv
  104. Type: `boolean`<br>
  105. Default: `true`
  106. Set to `false` if you don't want to extend the environment variables when providing the `env` property.
  107. #### argv0
  108. Type: `string`
  109. Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.
  110. #### stdio
  111. Type: `string[]` `string`<br>
  112. Default: `pipe`
  113. Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
  114. #### detached
  115. Type: `boolean`
  116. 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).
  117. #### uid
  118. Type: `number`
  119. Sets the user identity of the process.
  120. #### gid
  121. Type: `number`
  122. Sets the group identity of the process.
  123. #### shell
  124. Type: `boolean` `string`<br>
  125. Default: `false`
  126. If `true`, runs `command` 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.
  127. #### stripEof
  128. Type: `boolean`<br>
  129. Default: `true`
  130. [Strip EOF](https://github.com/sindresorhus/strip-eof) (last newline) from the output.
  131. #### preferLocal
  132. Type: `boolean`<br>
  133. Default: `true`
  134. Prefer locally installed binaries when looking for a binary to execute.<br>
  135. If you `$ npm install foo`, you can then `execa('foo')`.
  136. #### localDir
  137. Type: `string`<br>
  138. Default: `process.cwd()`
  139. Preferred path to find locally installed binaries in (use with `preferLocal`).
  140. #### input
  141. Type: `string` `Buffer` `stream.Readable`
  142. Write some input to the `stdin` of your binary.<br>
  143. Streams are not allowed when using the synchronous methods.
  144. #### reject
  145. Type: `boolean`<br>
  146. Default: `true`
  147. Setting this to `false` resolves the promise with the error instead of rejecting it.
  148. #### cleanup
  149. Type: `boolean`<br>
  150. Default: `true`
  151. Keep track of the spawned process and `kill` it when the parent process exits.
  152. #### encoding
  153. Type: `string`<br>
  154. Default: `utf8`
  155. Specify the character encoding used to decode the `stdout` and `stderr` output.
  156. #### timeout
  157. Type: `number`<br>
  158. Default: `0`
  159. 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.
  160. #### buffer
  161. Type: `boolean`<br>
  162. Default: `true`
  163. Buffer the output from the spawned process. When buffering is disabled you must consume the output of the `stdout` and `stderr` streams because the promise will not be resolved/rejected until they have completed.
  164. #### maxBuffer
  165. Type: `number`<br>
  166. Default: `10000000` (10MB)
  167. Largest amount of data in bytes allowed on `stdout` or `stderr`.
  168. #### killSignal
  169. Type: `string` `number`<br>
  170. Default: `SIGTERM`
  171. Signal value to be used when the spawned process will be killed.
  172. #### stdin
  173. Type: `string` `number` `Stream` `undefined` `null`<br>
  174. Default: `pipe`
  175. Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
  176. #### stdout
  177. Type: `string` `number` `Stream` `undefined` `null`<br>
  178. Default: `pipe`
  179. Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
  180. #### stderr
  181. Type: `string` `number` `Stream` `undefined` `null`<br>
  182. Default: `pipe`
  183. Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
  184. #### windowsVerbatimArguments
  185. Type: `boolean`<br>
  186. Default: `false`
  187. 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`.
  188. ## Tips
  189. ### Save and pipe output from a child process
  190. Let's say you want to show the output of a child process in real-time while also saving it to a variable.
  191. ```js
  192. const execa = require('execa');
  193. const getStream = require('get-stream');
  194. const stream = execa('echo', ['foo']).stdout;
  195. stream.pipe(process.stdout);
  196. getStream(stream).then(value => {
  197. console.log('child output:', value);
  198. });
  199. ```
  200. ## License
  201. MIT © [Sindre Sorhus](https://sindresorhus.com)