如何在 Deno 中获取命令的输出?

Won*_*Hau 6 deno

例如,假设我有以下代码:

Deno.run({cmd: ['echo', 'hello']})
Run Code Online (Sandbox Code Playgroud)

如何收集该命令的输出hello

Mar*_*nde 9

Deno.run返回 的一个实例Deno.Process。使用该方法.output()获取缓冲输出。如果您想阅读内容,请不要忘记传递"piped"stdout/stderr选项。

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

const output = await cmd.output() // "piped" must be set

cmd.close(); // Don't forget to close it
Run Code Online (Sandbox Code Playgroud)

.output()返回 aPromise解析为 a Uint8Arrayso 如果您希望输出为 UTF-8 字符串,则需要使用TextDecoder

const outStr = new TextDecoder().decode(output); // hello
Run Code Online (Sandbox Code Playgroud)