source: frontend/node_modules/execa/readme.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 19.3 KB
Line 
1<img src="media/logo.svg" width="400">
2<br>
3
4[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/execa)
5
6> Process execution for humans
7
8## Why
9
10This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:
11
12- Promise interface.
13- [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.
14- Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform.
15- [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why)
16- Higher max buffer. 100 MB instead of 200 KB.
17- [Executes locally installed binaries by name.](#preferlocal)
18- [Cleans up spawned processes when the parent process dies.](#cleanup)
19- [Get interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal. [*(Async only)*](#execasyncfile-arguments-options)
20- [Can specify file and arguments as a single string without a shell](#execacommandcommand-options)
21- More descriptive errors.
22
23## Install
24
25```
26$ npm install execa
27```
28
29## Usage
30
31```js
32const execa = require('execa');
33
34(async () => {
35 const {stdout} = await execa('echo', ['unicorns']);
36 console.log(stdout);
37 //=> 'unicorns'
38})();
39```
40
41### Pipe the child process stdout to the parent
42
43```js
44const execa = require('execa');
45
46execa('echo', ['unicorns']).stdout.pipe(process.stdout);
47```
48
49### Handling Errors
50
51```js
52const execa = require('execa');
53
54(async () => {
55 // Catching an error
56 try {
57 await execa('unknown', ['command']);
58 } catch (error) {
59 console.log(error);
60 /*
61 {
62 message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
63 errno: -2,
64 code: 'ENOENT',
65 syscall: 'spawn unknown',
66 path: 'unknown',
67 spawnargs: ['command'],
68 originalMessage: 'spawn unknown ENOENT',
69 shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
70 command: 'unknown command',
71 escapedCommand: 'unknown command',
72 stdout: '',
73 stderr: '',
74 all: '',
75 failed: true,
76 timedOut: false,
77 isCanceled: false,
78 killed: false
79 }
80 */
81 }
82
83})();
84```
85
86### Cancelling a spawned process
87
88```js
89const execa = require('execa');
90
91(async () => {
92 const subprocess = execa('node');
93
94 setTimeout(() => {
95 subprocess.cancel();
96 }, 1000);
97
98 try {
99 await subprocess;
100 } catch (error) {
101 console.log(subprocess.killed); // true
102 console.log(error.isCanceled); // true
103 }
104})()
105```
106
107### Catching an error with the sync method
108
109```js
110try {
111 execa.sync('unknown', ['command']);
112} catch (error) {
113 console.log(error);
114 /*
115 {
116 message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
117 errno: -2,
118 code: 'ENOENT',
119 syscall: 'spawnSync unknown',
120 path: 'unknown',
121 spawnargs: ['command'],
122 originalMessage: 'spawnSync unknown ENOENT',
123 shortMessage: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
124 command: 'unknown command',
125 escapedCommand: 'unknown command',
126 stdout: '',
127 stderr: '',
128 all: '',
129 failed: true,
130 timedOut: false,
131 isCanceled: false,
132 killed: false
133 }
134 */
135}
136```
137
138### Kill a process
139
140Using SIGTERM, and after 2 seconds, kill it with SIGKILL.
141
142```js
143const subprocess = execa('node');
144
145setTimeout(() => {
146 subprocess.kill('SIGTERM', {
147 forceKillAfterTimeout: 2000
148 });
149}, 1000);
150```
151
152## API
153
154### execa(file, arguments, options?)
155
156Execute 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).
157
158No escaping/quoting is needed.
159
160Unless 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.
161
162Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which:
163 - is also a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).
164 - exposes the following additional methods and properties.
165
166#### kill(signal?, options?)
167
168Same 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`.
169
170##### options.forceKillAfterTimeout
171
172Type: `number | false`\
173Default: `5000`
174
175Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
176
177Can be disabled with `false`.
178
179#### cancel()
180
181Similar 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`.
182
183#### all
184
185Type: `ReadableStream | undefined`
186
187Stream 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).
188
189This is `undefined` if either:
190 - the [`all` option](#all-2) is `false` (the default value)
191 - 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)
192
193### execa.sync(file, arguments?, options?)
194
195Execute a file synchronously.
196
197Returns or throws a [`childProcessResult`](#childProcessResult).
198
199### execa.command(command, options?)
200
201Same 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')`.
202
203If 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.
204
205The [`shell` option](#shell) must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.
206
207### execa.commandSync(command, options?)
208
209Same as [`execa.command()`](#execacommand-command-options) but synchronous.
210
211Returns or throws a [`childProcessResult`](#childProcessResult).
212
213### execa.node(scriptPath, arguments?, options?)
214
215Execute a Node.js script as a child process.
216
217Same 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)):
218 - 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.
219 - the [`shell`](#shell) option cannot be used
220 - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)
221
222### childProcessResult
223
224Type: `object`
225
226Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.
227
228The child process [fails](#failed) when:
229- its [exit code](#exitcode) is not `0`
230- it was [killed](#killed) with a [signal](#signal)
231- [timing out](#timedout)
232- [being canceled](#iscanceled)
233- there's not enough memory or there are already too many child processes
234
235#### command
236
237Type: `string`
238
239The file and arguments that were run, for logging purposes.
240
241This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).
242
243#### escapedCommand
244
245Type: `string`
246
247Same as [`command`](#command) but escaped.
248
249This is meant to be copy and pasted into a shell, for debugging purposes.
250Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).
251
252#### exitCode
253
254Type: `number`
255
256The numeric exit code of the process that was run.
257
258#### stdout
259
260Type: `string | Buffer`
261
262The output of the process on stdout.
263
264#### stderr
265
266Type: `string | Buffer`
267
268The output of the process on stderr.
269
270#### all
271
272Type: `string | Buffer | undefined`
273
274The output of the process with `stdout` and `stderr` interleaved.
275
276This is `undefined` if either:
277 - the [`all` option](#all-2) is `false` (the default value)
278 - `execa.sync()` was used
279
280#### failed
281
282Type: `boolean`
283
284Whether the process failed to run.
285
286#### timedOut
287
288Type: `boolean`
289
290Whether the process timed out.
291
292#### isCanceled
293
294Type: `boolean`
295
296Whether the process was canceled.
297
298#### killed
299
300Type: `boolean`
301
302Whether the process was killed.
303
304#### signal
305
306Type: `string | undefined`
307
308The name of the signal that was used to terminate the process. For example, `SIGFPE`.
309
310If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.
311
312#### signalDescription
313
314Type: `string | undefined`
315
316A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.
317
318If 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.
319
320#### message
321
322Type: `string`
323
324Error 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.
325
326The child process [stderr](#stderr) then [stdout](#stdout) are appended to the end, separated with newlines and not interleaved.
327
328#### shortMessage
329
330Type: `string`
331
332This is the same as the [`message` property](#message) except it does not include the child process stdout/stderr.
333
334#### originalMessage
335
336Type: `string | undefined`
337
338Original 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.
339
340This is `undefined` unless the child process exited due to an `error` event or a timeout.
341
342### options
343
344Type: `object`
345
346#### cleanup
347
348Type: `boolean`\
349Default: `true`
350
351Kill the spawned process when the parent process exits unless either:
352 - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)
353 - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit
354
355#### preferLocal
356
357Type: `boolean`\
358Default: `false`
359
360Prefer locally installed binaries when looking for a binary to execute.\
361If you `$ npm install foo`, you can then `execa('foo')`.
362
363#### localDir
364
365Type: `string`\
366Default: `process.cwd()`
367
368Preferred path to find locally installed binaries in (use with `preferLocal`).
369
370#### execPath
371
372Type: `string`\
373Default: `process.execPath` (Current Node.js executable)
374
375Path to the Node.js executable to use in child processes.
376
377This can be either an absolute path or a path relative to the [`cwd` option](#cwd).
378
379Requires [`preferLocal`](#preferlocal) to be `true`.
380
381For 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.
382
383#### buffer
384
385Type: `boolean`\
386Default: `true`
387
388Buffer 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.
389
390If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), and [`error.all`](#all) will contain the buffered data.
391
392#### input
393
394Type: `string | Buffer | stream.Readable`
395
396Write some input to the `stdin` of your binary.\
397Streams are not allowed when using the synchronous methods.
398
399#### stdin
400
401Type: `string | number | Stream | undefined`\
402Default: `pipe`
403
404Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
405
406#### stdout
407
408Type: `string | number | Stream | undefined`\
409Default: `pipe`
410
411Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
412
413#### stderr
414
415Type: `string | number | Stream | undefined`\
416Default: `pipe`
417
418Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
419
420#### all
421
422Type: `boolean`\
423Default: `false`
424
425Add 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.
426
427#### reject
428
429Type: `boolean`\
430Default: `true`
431
432Setting this to `false` resolves the promise with the error instead of rejecting it.
433
434#### stripFinalNewline
435
436Type: `boolean`\
437Default: `true`
438
439Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.
440
441#### extendEnv
442
443Type: `boolean`\
444Default: `true`
445
446Set to `false` if you don't want to extend the environment variables when providing the `env` property.
447
448---
449
450Execa 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)
451
452#### cwd
453
454Type: `string`\
455Default: `process.cwd()`
456
457Current working directory of the child process.
458
459#### env
460
461Type: `object`\
462Default: `process.env`
463
464Environment key-value pairs. Extends automatically from `process.env`. Set [`extendEnv`](#extendenv) to `false` if you don't want this.
465
466#### argv0
467
468Type: `string`
469
470Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified.
471
472#### stdio
473
474Type: `string | string[]`\
475Default: `pipe`
476
477Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
478
479#### serialization
480
481Type: `string`\
482Default: `'json'`
483
484Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execa.node()`](#execanodescriptpath-arguments-options):
485 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.
486 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
487
488Requires Node.js `13.2.0` or later.
489
490[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
491
492#### detached
493
494Type: `boolean`
495
496Prepare 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).
497
498#### uid
499
500Type: `number`
501
502Sets the user identity of the process.
503
504#### gid
505
506Type: `number`
507
508Sets the group identity of the process.
509
510#### shell
511
512Type: `boolean | string`\
513Default: `false`
514
515If `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.
516
517We recommend against using this option since it is:
518- not cross-platform, encouraging shell-specific syntax.
519- slower, because of the additional shell interpretation.
520- unsafe, potentially allowing command injection.
521
522#### encoding
523
524Type: `string | null`\
525Default: `utf8`
526
527Specify 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.
528
529#### timeout
530
531Type: `number`\
532Default: `0`
533
534If 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.
535
536#### maxBuffer
537
538Type: `number`\
539Default: `100_000_000` (100 MB)
540
541Largest amount of data in bytes allowed on `stdout` or `stderr`.
542
543#### killSignal
544
545Type: `string | number`\
546Default: `SIGTERM`
547
548Signal value to be used when the spawned process will be killed.
549
550#### windowsVerbatimArguments
551
552Type: `boolean`\
553Default: `false`
554
555If `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`.
556
557#### windowsHide
558
559Type: `boolean`\
560Default: `true`
561
562On 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.
563
564#### nodePath *(For `.node()` only)*
565
566Type: `string`\
567Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath)
568
569Node.js executable used to create the child process.
570
571#### nodeOptions *(For `.node()` only)*
572
573Type: `string[]`\
574Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv)
575
576List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.
577
578## Tips
579
580### Retry on error
581
582Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:
583
584```js
585const pRetry = require('p-retry');
586
587const run = async () => {
588 const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
589 return results;
590};
591
592(async () => {
593 console.log(await pRetry(run, {retries: 5}));
594})();
595```
596
597### Save and pipe output from a child process
598
599Let's say you want to show the output of a child process in real-time while also saving it to a variable.
600
601```js
602const execa = require('execa');
603
604const subprocess = execa('echo', ['foo']);
605subprocess.stdout.pipe(process.stdout);
606
607(async () => {
608 const {stdout} = await subprocess;
609 console.log('child output:', stdout);
610})();
611```
612
613### Redirect output to a file
614
615```js
616const execa = require('execa');
617
618const subprocess = execa('echo', ['foo'])
619subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))
620```
621
622### Redirect input from a file
623
624```js
625const execa = require('execa');
626
627const subprocess = execa('cat')
628fs.createReadStream('stdin.txt').pipe(subprocess.stdin)
629```
630
631### Execute the current package's binary
632
633```js
634const {getBinPathSync} = require('get-bin-path');
635
636const binPath = getBinPathSync();
637const subprocess = execa(binPath);
638```
639
640`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.
641
642## Related
643
644- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for `execa`
645- [nvexeca](https://github.com/ehmicky/nvexeca) - Run `execa` using any Node.js version
646- [sudo-prompt](https://github.com/jorangreef/sudo-prompt) - Run commands with elevated privileges.
647
648## Maintainers
649
650- [Sindre Sorhus](https://github.com/sindresorhus)
651- [@ehmicky](https://github.com/ehmicky)
652
653---
654
655<div align="center">
656 <b>
657 <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>
658 </b>
659 <br>
660 <sub>
661 Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
662 </sub>
663</div>
Note: See TracBrowser for help on using the repository browser.