From 4caad41fa62b94290ab70e6903738468e506be44 Mon Sep 17 00:00:00 2001 From: Evan Shortiss Date: Sun, 12 May 2024 00:18:40 -0700 Subject: [PATCH] doc: add example for `execFileSync` method and ref to stdio Added an example to the `execFileSync` method. This demonstrates how to handle exceptions and access the stderr and stdio properties that are attached to the `Error` object in a `catch` block. Added a link to the detailed stdio section nested under `child_process.spawn()` from each child_process sync method option description. Fixes: https://github.com/nodejs/node/issues/39306 PR-URL: https://github.com/nodejs/node/pull/39412 Reviewed-By: James M Snell Reviewed-By: Gireesh Punathil Reviewed-By: Matteo Collina Reviewed-By: Antoine du Hamel --- doc/api/child_process.md | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 50ab445ed533fe..b08ba65917aadc 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -921,7 +921,8 @@ changes: * `input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`. - * `stdio` {string|Array} Child's stdio configuration. `stderr` by default will + * `stdio` {string|Array} Child's stdio configuration. + See [`child_process.spawn()`][]'s [`stdio`][]. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`. * `env` {Object} Environment key-value pairs. **Default:** `process.env`. @@ -962,6 +963,34 @@ If the process times out or has a non-zero exit code, this method will throw an function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** +```js +const { execFileSync } = require('node:child_process'); + +try { + const stdout = execFileSync('my-script.sh', ['my-arg'], { + // Capture stdout and stderr from child process. Overrides the + // default behavior of streaming child stderr to the parent stderr + stdio: 'pipe', + + // Use utf8 encoding for stdio pipes + encoding: 'utf8', + }); + + console.log(stdout); +} catch (err) { + if (err.code) { + // Spawning child process failed + console.error(err.code); + } else { + // Child was spawned but exited with non-zero exit code + // Error contains any stdout and stderr from the child + const { stdout, stderr } = err; + + console.error({ stdout, stderr }); + } +} +``` + ### `child_process.execSync(command[, options])`