乐闻世界logo
搜索文章和话题

How do I run an arbitrary shell command from Deno?

1个答案

1

Running any shell command in Deno can be achieved by using the Deno.run method from the standard library. This method allows you to specify the command and its arguments, and control how the command is executed. Below is a specific example:

Example Code

Suppose we want to run a simple shell command in Deno, such as echo "Hello, World!".

typescript
// First, ensure that the script has the necessary permissions to execute commands when running the Deno script. // You can grant permissions by using the `--allow-run` flag in the command line. // deno run --allow-run=echo index.ts // The script content is as follows: const cmd = "echo"; const args = ["Hello, World!"]; const process = Deno.run({ cmd: [cmd, ...args], // Combine the command and argument array }); await process.status(); // Wait for the command to complete process.close(); // Close the process resources

Detailed Explanation

  1. Permission Control:

    • Before using Deno.run, ensure that the script has the necessary permissions to execute external commands. This is achieved by adding the --allow-run flag at runtime. For security considerations, specific commands can also be specified after --allow-run, such as --allow-run=echo which only allows executing the echo command.
  2. Creating the Command:

    • The Deno.run method accepts an object where the cmd property is an array containing the command and its arguments.
  3. Execution and Resource Management:

    • await process.status() is an asynchronous operation that waits for the command to complete.
    • After execution, use process.close() to ensure that resources occupied by this process are released.

Security Tips

  • When using Deno.run to execute shell commands, be cautious with input parameters to avoid injection attacks.
  • Limiting command execution permissions to only necessary commands can reduce security risks.

Through this approach, Deno provides a relatively secure and flexible way to run external commands while maintaining fine-grained control over resources.

2024年7月20日 18:56 回复

你的答案