web 3d图形渲染器
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.

656 lines
19 KiB

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