首页 > 解决方案 > 如何从 Deno 运行任意 shell 命令?

问题描述

我想从 Deno 运行任意 bash 命令,就像在 Node.js 中一样child_process。在 Deno 有可能吗?

标签: deno

解决方案


为了运行 shell 命令,您必须使用Deno.run,这需要--allow-run权限。

有一个正在进行的讨论可以用来--allow-all代替运行子进程


以下将输出到stdout.

// --allow-run
const process = Deno.run({
  cmd: ["echo", "hello world"]
});

// Close to release Deno's resources associated with the process.
// The process will continue to run after close(). To wait for it to
// finish `await process.status()` or `await process.output()`.
process.close();

如果要存储输出,则必须设置stdout/stderr"piped"

const process = Deno.run({
  cmd: ["echo", "hello world"], 
  stdout: "piped",
  stderr: "piped"
});


const output = await process.output() // "piped" must be set
const outStr = new TextDecoder().decode(output);

/* 
const error = await p.stderrOutput();
const errorStr = new TextDecoder().decode(error); 
*/

process.close();

推荐阅读