Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions examples/scripts/subprocesses_spawn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*
* For more complex usecases, we don't simply want the output of some
* command. In this case, we can spawn a subprocess and interact with
* it.
* it using convenience methods for reading output streams.
*/

// The Deno namespace has a unified api for interacting with the outside system
Expand Down Expand Up @@ -36,6 +36,9 @@ writer.releaseLock();
// We must then close stdin
await process.stdin.close();

// We can now wait for the process to output the results
const result = await process.output();
console.log(new TextDecoder().decode(result.stdout));
// We can now wait for the process to output the results using convenience methods
const stdout = await process.stdout.text();
console.log(stdout);

// Wait for the process to complete
await process.status;
52 changes: 52 additions & 0 deletions examples/tutorials/subprocess.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,55 @@ Run it:
```shell
$ deno run --allow-run=yes --allow-read=. --allow-write=. ./subprocess_piping_to_file.ts
```

## Reading subprocess output with convenience methods

When working with spawned subprocesses, you can use convenience methods on the
`stdout` and `stderr` streams to easily collect and parse output. These methods
are similar to those available on `Response` objects:

```ts title="subprocess_convenience_methods.ts"
const command = new Deno.Command("deno", {
args: [
"eval",
"console.log(JSON.stringify({message: 'Hello from subprocess'}))",
],
stdout: "piped",
stderr: "piped",
});

const process = command.spawn();

// Use convenience methods to collect output
const stdoutText = await process.stdout.text();
const stderrText = await process.stderr.text();

console.log("stdout:", stdoutText);
console.log("stderr:", stderrText);

// Wait for the process to complete
const status = await process.status;
console.log("Exit code:", status.code);
```

Available convenience methods include:

- `.text()` - Returns the output as a UTF-8 string
- `.bytes()` - Returns the output as a `Uint8Array`
- `.arrayBuffer()` - Returns the output as an `ArrayBuffer`
- `.json()` - Parses the output as JSON and returns the parsed object

```ts title="subprocess_json_parsing.ts"
const command = new Deno.Command("deno", {
args: ["eval", "console.log(JSON.stringify({name: 'Deno', version: '2.0'}))"],
stdout: "piped",
});

const process = command.spawn();

// Parse JSON output directly
const jsonOutput = await process.stdout.json();
console.log("Parsed JSON:", jsonOutput); // { name: "Deno", version: "2.0" }

await process.status;
```