In Deno, generating child processes and communicating with them can be achieved using the Deno.run method. This method allows you to launch a new child process and interact with the standard input/output streams (stdin, stdout, stderr) between the main and child processes. The following example demonstrates how to create a child process in Deno to execute a simple shell command and read its output results:
Example: Creating a Child Process and Reading Output in Deno
-
First, ensure your Deno environment is properly configured with the necessary runtime permissions.
In this example, we'll use the
lscommand to list the contents of the current directory, which does not require additional file system permissions. -
Write the code:
typescript// Create a child process to execute the `ls` command const process = Deno.run({ cmd: ["ls"], // Specify the command and its arguments in an array stdout: "piped", // Configure stdout as a pipe to read the output stderr: "piped" // Configure stderr as a pipe for error handling }); // Read and decode the child process's output const output = await process.output(); // Wait for stdout stream const outStr = new TextDecoder().decode(output); // Decode Uint8Array to string // Error handling: Read and decode the child process's error output const errorOutput = await process.stderrOutput(); const errorStr = new TextDecoder().decode(errorOutput); // Output the results of the child process console.log("stdout:", outStr); if (errorStr) { console.log("stderr:", errorStr); } // Close the child process's streams and wait for it to complete process.close(); const status = await process.status(); // Wait for process completion and retrieve exit status console.log("Process exited with status", status.code);
- Run the code:
Use the following command in the terminal to execute your Deno script, assuming the script file is named run_ls.ts:
bashdeno run --allow-run run_ls.ts
Here, --allow-run is the required permission flag enabling Deno to execute child processes.
Summary:
In this example, we used Deno's API to launch a child process and capture its standard output and error output through pipes. This method is highly effective for executing external programs and processing their output, and can be used for various automation scripts and system management tasks. Through proper permission management, Deno offers developers a secure way to perform these operations.